Elasticsearch按字段分组以获取值的首次出现

2024-09-30 00:40:15 发布

您现在位置:Python中文网/ 问答频道 /正文

抱歉,如果我的问题可能是重复的,我只是没有找到任何类似的。你知道吗

我通过Python向Elasticsearch发送请求。你知道吗

这是我的密码:

import json
import requests

query = {
 "size": 5,
 "_source": ["UserId", "Name", "Status"],
 "query": {
   "match_all": {
   }
 }
}

query = json.dumps(query) 

response = requests.get(f'{ES_URL}/{ES_INDEX}/_search',
                        headers={'Content-Type': 'application/json'},
                        data=query)

我的回答是:

{'took': 16,
 'timed_out': False,
 '_shards': {'total': 5, 'successful': 5, 'skipped': 0, 'failed': 0},
 'hits': {'total': 2069099,
  'max_score': 1.0,
  'hits': [{'_index': 'index2',
    '_type': 'indexresult',
    '_id': '8768768',
    '_score': 1.0,
    '_source': {'UserId': 4264151, 'Name': 'Victor', 'Status': 'High'}},
   {'_index': 'index2',
    '_type': 'indexresult',
    '_id': '5463255',
    '_score': 1.0,
    '_source': {'UserId': 4264151, 'Name': 'Victor', 'Status': 'Medium'}},
   {'_index': 'index2',
    '_type': 'indexresult',
    '_id': '2323564',
    '_score': 1.0,
    '_source': {'UserId': 4327653, 'Name': 'John', 'Status': 'Medium'}},
   {'_index': 'index2',
    '_type': 'indexresult',
    '_id': '3564123',
    '_score': 1.0,
    '_source': {'UserId': 4327653, 'Name': 'John', 'Status': 'Low'}},
   {'_index': 'index2',
    '_type': 'indexresult',
    '_id': '4456256',
    '_score': 1.0,
    '_source': {'UserId': 7893231, 'Name': 'Sebastian', 'Status': 'Low'}]}}

响应包含两个重复的值UserId42641514327653)。你知道吗

问题:需要在Elasticsearch查询中编写什么来仅获取唯一的UserId值(例如,返回随机或第一次出现的UserId)?你知道吗

也就是说,我希望反应是这样的:

{'took': 16,
 'timed_out': False,
 '_shards': {'total': 5, 'successful': 5, 'skipped': 0, 'failed': 0},
 'hits': {'total': 2069099,
  'max_score': 1.0,
  'hits': [{'_index': 'index2',
    '_type': 'indexresult',
    '_id': '8768768',
    '_score': 1.0,
    '_source': {'UserId': 4264151, 'Name': 'Victor', 'Status': 'High'}},
   {'_index': 'index2',
    '_type': 'indexresult',
    '_id': '2323564',
    '_score': 1.0,
    '_source': {'UserId': 4327653, 'Name': 'John', 'Status': 'Medium'}}
   {'_index': 'index2',
    '_type': 'indexresult',
    '_id': '4456256',
    '_score': 1.0,
    '_source': {'UserId': 7893231, 'Name': 'Sebastian', 'Status': 'Low'}]}}

Tags: nameidjsonsourceindextypestatusquery
1条回答
网友
1楼 · 发布于 2024-09-30 00:40:15

您可以使用field collapsing and expanded results

将您的查询重写到下面,对于每个用户,您将得到一个文档:

query = {
  "size": 5,
  "_source": false
  "query": {
    "match_all": {
    }
  },
  "collapse" : {
    "field" : "UserId", 
    "inner_hits": {
        "name": "last", 
        "size": 1, 
        "_source": ["UserId", "Name", "Status"],
        "sort": [{ "_id": "desc" }] 
    }
  }
}

相关问题 更多 >

    热门问题