????????有時(shí)候使用es查詢出的結(jié)果包含多個(gè)字段,如果數(shù)據(jù)中僅僅包含幾個(gè)字段時(shí),我們是很容易挑出自己需要的字段值,但是如果數(shù)據(jù)中包含幾十或者幾百甚至更多時(shí),尤其是數(shù)據(jù)中嵌套好多層時(shí),不容易直接挑取出需要的值,這時(shí)候可以借助程序直接查找出來?;蛘哚槍?duì)性的直接查詢時(shí)就限定條件查詢某些字段的值。
直接從es中查詢出的示例數(shù)據(jù):
{
"took": 918,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 4,
"relation": "eq"
},
"max_score": 1.0,
"hits": [{
"_index": "test",
"_type": "user",
"_id": "QHi1UoIBpyNh4YQ4T1Sq",
"_score": 1.0,
"_source": {
"id": 1001,
"name": "張三",
"age": 20,
"sex": "男",
"grade": {
"Chinese": 99,
"Math": 98,
"English": 96
}
}
},
{
"_index": "test",
"_type": "user",
"_id": "1002",
"_score": 1.0,
"_source": {
"id": 1002,
"name": "李四",
"age": 23,
"sex": "女",
"grade": {
"Chinese": 98,
"Math": 99,
"English": 97
}
}
},
{
"_index": "test",
"_type": "user",
"_id": "1003",
"_score": 1.0,
"_source": {
"id": 1003,
"name": "王五",
"age": 27,
"sex": "男",
"grade": {
"Chinese": 93,
"Math": 90,
"English": 99
}
}
},
{
"_index": "test",
"_type": "user",
"_id": "1004",
"_score": 1.0,
"_source": {
"id": 1004,
"name": "趙六",
"age": 29,
"sex": "女",
"grade": {
"Chinese": 100,
"Math": 95,
"English": 94
}
}
}
]
}
}
使用python打印出需要的字段值:
import json
import jmespath
with open('text.txt', 'r', encoding='utf-8') as f:
data = f.read()
json_data = json.loads(data)
# print(json_data)
sources = json_data.get('hits').get('hits')
# print(sources)
for source in sources:
# print(source)
data = source.get('_source')
print(data)
valid_fields = '{name: name, Chinese_grade: grade.Chinese}'
ret = jmespath.search(valid_fields, data)
print(ret)
運(yùn)行結(jié)果:
注意:使用json.load()時(shí),會(huì)把文本中的fase、true直接變?yōu)镕alse、True
參考博文:文章來源:http://www.zghlxwxcb.cn/news/detail-521005.html
python中jmespath庫(kù)用法詳解_IT之一小佬的博客-CSDN博客_jmespath python文章來源地址http://www.zghlxwxcb.cn/news/detail-521005.html
到了這里,關(guān)于es查詢響應(yīng)結(jié)果中獲取某些字段的值的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!