写入数据
from elasticsearch import Elasticsearch
es = Elasticsearch()
body1={
"first_name" : "John",
"last_name" : "Smith",
"age" : 25,
"about" : "I love to go rock climbing",
"interests": [ "sports", "music" ]
}
#余下代码为写入三段数据
body2={
"first_name" : "Jane",
"last_name" : "Smith",
"age" : 32,
"about" : "I like to collect rock albums",
"interests": [ "music" ]
}
body3={
"first_name" : "Douglas",
"last_name" : "Fir",
"age" : 35,
"about": "I like to build cabinets",
"interests": [ "forestry" ]
}
res1 = es.index(index="megacorp", doc_type='employee', id=1,body=body1)
res2 = es.index(index="megacorp", doc_type='employee', id=2,body=body2)
res3 = es.index(index="megacorp", doc_type='employee', id=3,body=body3)
这是一个elasticsearch的简单查询,要求匹配 名字为”Smith”的文档,有没有和mongodb有点像.
bb1={
"query" : {
"match" : {"last_name" : "Smith" }
}
}
rt1= es.search(index="megacorp", body=bb1)
print(rt1)
Out[11]:
{'_shards': {'failed': 0, 'skipped': 0, 'successful': 5, 'total': 5},
'hits': {'hits': [{'_id': '2',
'_index': 'megacorp',
'_score': 0.2876821,
'_source': {'about': 'I like to collect rock albums',
'age': 32,
'first_name': 'Jane',
'interests': ['music'],
'last_name': 'Smith'},
'_type': 'employee'},
{'_id': '1',
'_index': 'megacorp',
'_score': 0.2876821,
'_source': {'about': 'I love to go rock climbing',
'age': 25,
'first_name': 'John',
'interests': ['sports', 'music'],
'last_name': 'Smith'},
'_type': 'employee'}],
'max_score': 0.2876821,
'total': 2},
'timed_out': False,
'took': 309}
现在尝试下更复杂的搜索。 同样搜索姓氏为 Smith 的雇员,但这次我们只需要年龄大于 30 的。查询需要稍作调整,使用过滤器 filter ,它支持高效地执行一个结构化查询。
bb2={
"query" : {
"bool": {
"must": { "match" : { "last_name" : "smith" }
},
"filter": {
"range" : {
"age" : { "gt" : 30 }
}
}
}
}
}
rt2= es.search(index="megacorp", body=bb2)
print(rt2)
{'took': 23, 'timed_out': False, '_shards': {'total': 5, 'successful': 5, 'skipped': 0, 'failed': 0}, 'hits': {'total': 1, 'max_score': 0.2876821, 'hits': [{'_index': 'megacorp', '_type': 'employee', '_id': '2', '_score': 0.2876821, '_source': {'first_name': 'Jane', 'last_name': 'Smith', 'age': 32, 'about': 'I like to collect rock albums', 'interests': ['music']}}]}}