lem*_*mon 1 python elasticsearch
抱歉,如果我的问题可能重复,我只是没有发现任何类似的问题。
我通过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)
Run Code Online (Sandbox Code Playgroud)
这是我的回应:
{'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'}]}}
Run Code Online (Sandbox Code Playgroud)
响应包含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'}]}}
Run Code Online (Sandbox Code Playgroud)
您可以使用字段折叠和展开结果:
将查询重写为以下内容,每位用户将获得一个文档:
query = {
"size": 5,
"_source": false
"query": {
"match_all": {
}
},
"collapse" : {
"field" : "UserId",
"inner_hits": {
"name": "last",
"size": 1,
"_source": ["UserId", "Name", "Status"],
"sort": [{ "_id": "desc" }]
}
}
}
Run Code Online (Sandbox Code Playgroud)