抱歉,如果我的问题可能重复,我只是没有找到类似的内容。
我通过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'}]}}
响应包含 UserId
值的两次重复( 4264151
和 4327653
)。
问题:需要在 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'}]}}
最佳答案
您可以使用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" }]
}
}
}
关于python - Elasticsearch 按字段分组以获取第一次出现的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57788922/