python elasticsearch 入门教程(一)
生活随笔
收集整理的這篇文章主要介紹了
python elasticsearch 入门教程(一)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
寫入數據
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']}}]}}總結
以上是生活随笔為你收集整理的python elasticsearch 入门教程(一)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: elasticsearch pytho
- 下一篇: python elasticsearch