代码之家  ›  专栏  ›  技术社区  ›  John Smith Optional

Elasticsearch:如何获取按匹配分数排序的字段的最高唯一值?

  •  3
  • John Smith Optional  · 技术社区  · 8 年前

    postcode , city , street streetnumber name 我想当用户输入邮政编码、城市和对街道的一些查询时,可以建议一个街道列表。

    postcode: 75010
    city: Paris
    street: rue des
    

    我想要一张街道的名单

    'rue des petites écuries'
    'rue des messageries'
    ...
    'rue du faubourg poissonnière'
    ...
    

    我可以向用户建议。

    返回文档的查询如下所示:

    {
        "query": {
            "bool": {
                "must": [
                    {{"term": {"postcode": "75010"}},
                    {{"term": {city": "Paris"}},
                    {{"match": {"street": "rue des"}}
                ]    
            }
         }
    }
    

    但当然,同一条街会出现很多次,因为每个街道都可以在集合中的不同地址出现多次。

    我尝试使用“聚合”框架并添加了一个aggs:

    {
        "query": {
            "bool": {
                "must": [
                    {{"term": {"postcode": "75010"}},
                        {{"term": {city": "Paris"}},
                        {{"match": {"street": "rue des"}}
                ]    
            }
         },
         "aggs": {
            "street_agg": {
                "terms": {
                    "field": "street",
                    "size": 10
                 }
             }           
         }
    }
    

    1 回复  |  直到 8 年前
        1
  •  4
  •   John Smith Optional    8 年前

    好的,所以解决方案可以在 Elasticsearch aggregation order by top hit score 但前提是你读了Shadocko的评论: Elasticsearch aggregation order by top hit score ,但我没有。

    因此,对于任何感兴趣的人和我未来的自己,这里有一个解决方案:

    {                                 
        'query': {
            'bool': {
                'must': [
                    {'term': {'postcode': '75010'}},
                    {'term': {'city': 'Paris'}},
                    {'match': {'street.autocomplete': 'rue des'}}
                ]
             }
        },
        'aggs': {
            'street_agg': {
                'terms': {
                    'field': 'street',
                    'size': 10,
                    'order': {
                        'max_score': 'desc'
                    }
                },
                'aggs': {
                    'max_score': {
                        'max': {'script': '_score'}
                    }
                }
            }
        }
    }
    

    max 聚合函数,这意味着它进行不必要的计算(只需从bucket中取出一个文档的分数就足够了)。但似乎没有“选择一个”聚合函数,只是 min , 最大值 , avg sum