如何修改代码实现Elasticsearch返回结果按lastpost时间降序排序
问题解答
你的判断是对的,需要新增sort配置实现按lastpost时间降序排列,不需要把sort放在query参数下级,和size、query、_source平级放在搜索请求body的顶层即可。
两种常用排序场景修改方案
场景1:完全按lastpost降序排列(忽略原有语义相似度得分的排序优先级)
直接修改client.search的入参body,新增sort配置:
response = client.search( index=INDEX_NAME, body={ "size": SEARCH_SIZE, "query": script_query, "_source": {"includes": ["title", "id","lastpost"]}, "sort": [ {"lastpost": {"order": "desc"}} ] } )
场景2:优先按语义相似度得分降序,得分相同的内容再按lastpost降序排列
保留原有得分排序逻辑,叠加时间排序规则:
response = client.search( index=INDEX_NAME, body={ "size": SEARCH_SIZE, "query": script_query, "_source": {"includes": ["title", "id","lastpost"]}, "sort": [ {"_score": {"order": "desc"}}, {"lastpost": {"order": "desc"}} ] } )
注意事项
请提前确认Elasticsearch索引中的lastpost字段为date类型,否则时间排序可能会出现不符合预期的结果。
内容的提问来源于stack exchange,提问作者Beiwei
相关产品推荐
相关产品推荐

