如何根据ElasticSearch中的项目数量对搜索结果进行排序? [英] How do I sort the search results according to the number of items in ElasticSearch?

查看:501
本文介绍了如何根据ElasticSearch中的项目数量对搜索结果进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们在ElasticSearch中存储这样的文件:

  {
'name':'user name ',
'age':43,
'location':'CA,USA',
'bio':'into java,scala,python ..etc。',
'tags':['java','scala','python','django','lift']
}

让我们使用location = CA进行搜索,我可以根据'标签'中的项目数量对结果进行排序吗?



我想在第一页列出最多标签的人。

解决方案

你可以做它编制一个包含标签数量的附加字段,然后可以轻松地对结果进行排序。否则,如果您愿意在查询时支付一点性能成本,则有一个不错的解决方案,无需重新编制数据:您可以 sort 基于这样的脚本:

  {
query:{
match_all:{}
},
sort:{
_script:{
script :doc ['tags']。values.length,
type:number,
order:asc
}
}

您可以从基于脚本的排序部分中读取:

$ b $请注意,对于基于脚本的基于脚本的排序,建议使用
来替代使用custom_score查询,因​​为基于分数的排序更快。


这意味着最好使用自定义分数查询来影响你的分数,然后按分数排序,如下所示:



$ $ $ $ $ $ $ $ $$ {
查询:{
custom_score:{
查询:{
match_all }
},
script:_score * doc ['tags']。values.length
}
}
}


Let's say that I store documents like this in ElasticSearch:

{
    'name':'user name', 
    'age':43, 
    'location':'CA, USA', 
    'bio':'into java, scala, python ..etc.', 
    'tags':['java','scala','python','django','lift']
}

And let's say that I search using location=CA, how can I sort the results according to the number of the items in 'tags'?

I would like to list the people with the most number of tag in the first page.

解决方案

You can do it indexing an additional field which contains the number of tags, on which you can then easily sort your results. Otherwise, if you are willing to pay a little performance cost at query time there's a nice solution that doesn't require to reindex your data: you can sort based on a script like this:

{
    "query" : {
        "match_all" : {}
    },
    "sort" : {
        "_script" : { 
            "script" : "doc['tags'].values.length",
            "type" : "number",
            "order" : "asc"
        }
    }
}

As you can read from the script based sorting section:

Note, it is recommended, for single custom based script based sorting, to use custom_score query instead as sorting based on score is faster.

That means that it'd be better to use a custom score query to influence your score, and then sort by score, like this:

{
    "query" : {
        "custom_score" : {
            "query" : {
                "match_all" : {}
            },
            "script" : "_score * doc['tags'].values.length"
        }
    }
}

这篇关于如何根据ElasticSearch中的项目数量对搜索结果进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆