????????有時候想看看es中某個索引中所有的字段,直接通過查詢mapping是很難看出所有的字段的,里面包含的屬性太多了。本博文將實現(xiàn)獲取mapping中所有字段的算法。
示例new_user2索引中的mapping值:
{
"new_user2": {
"mappings": {
"properties": {
"address": {
"properties": {
"city": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"province": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
},
"age": {
"type": "long"
},
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}
}
示例代碼:【直接在mapping中獲取】
import json
with open('text.txt', 'r', encoding='utf-8') as f:
data = f.read()
json_data = json.loads(data)
# print(json_data)
for key, value in json_data.items():
index = key
mappings = value
def func(dic):
res = []
def traceback(mapping, fields_join):
if not isinstance(mapping, dict):
return res.append(fields_join)
for key, value in mapping.items():
if fields_join:
traceback(value, fields_join + '.' + key)
else:
traceback(value, key)
def filter_fields(fields: list):
fields_lst = []
for field in fields:
field = field.replace('mappings.properties.', '').replace('.properties', '')
# 注意:下面幾個判斷最好替換字符串長的在前面,防止出錯
if field[-28:] == '.fields.keyword.ignore_above':
field = field[:-28]
elif field[-20:] == '.fields.keyword.type':
field = field[:-20]
elif field[-15:] == '.fields.keyword':
field = field[:-15]
elif field[-5:] == '.type':
field = field[:-5]
fields_lst.append(field)
return list(set(fields_lst))
traceback(dic, '')
return filter_fields(res)
ret = func(mappings)
print("index: ", index)
print("fields: ", ret)
運行結(jié)果:
文章來源:http://www.zghlxwxcb.cn/news/detail-512692.html
注意:也可以直接通過查詢語句,直接在es中查詢,通過響應(yīng)的數(shù)據(jù)中獲?。簉es['hits']['hits']。但是,由于查詢出的數(shù)據(jù)未必所有字段都是有數(shù)據(jù)的,所有這種方法不是準(zhǔn)確的。最好還是直接從獲取到的_mapping中直接獲取!文章來源地址http://www.zghlxwxcb.cn/news/detail-512692.html
到了這里,關(guān)于es獲取mapping中所有的字段(回溯)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!