1. 程式人生 > >Elasticsearch Python API

Elasticsearch Python API

med blog 存在 1.0 elastics mps false cse earch

創建索引、插入數據

import json
from datetime import datetime
from elasticsearch import Elasticsearch
# 連接elasticsearch,默認是9200
es = Elasticsearch(hosts=10.240.1.103)
# 創建索引,索引的名字是my-index,如果已經存在了,就返回個400,
# 這個索引可以現在創建,也可以在後面插入數據的時候再臨時創建
es.indices.create(index=my-index)
# {u‘acknowledged‘:True}
#
插入數據 es.index(index="my-index", doc_type="test-type", id=1, body={"any": "data", "timestamp": datetime.now()}) # {u‘_type‘:u‘test-type‘,u‘created‘:True,u‘_shards‘:{u‘successful‘:1,u‘failed‘:0,u‘total‘:2},u‘_version‘:1,u‘_index‘:u‘my-index‘,u‘_id‘:u‘1}

檢索數據

# get獲取
res = es.get(index="my-index
", doc_type="test-type", id=1) print(json.dumps(res,indent=4)) """ { "_index": "my-index", "found": true, "_source": { "any": "data01", "timestamp": "2017-09-05T15:06:53.599863" }, "_id": "1", "_version": 3, "_type": "test-type" } """ # search獲取 res = es.search(index="
test-index", body={"query": {"match_all": {}}}) print(json.dumps(res,indent=4)) """ { "_shards": { "successful": 5, "total": 5, "failed": 0 }, "timed_out": false, "took": 2, "hits": { "total": 1, "hits": [ { "_source": { "any": "data", "timestamp": "2017-09-05T15:01:54.780318" }, "_index": "test-index", "_type": "test-type", "_id": "42", "_score": 1.0 } ], "max_score": 1.0 } } """ res = es.search(index="test-index", body={query: {match: {any: data}}}) # 獲取any=data的所有值 print(json.dumps(res,indent=4)) """ { "hits": { "hits": [ { "_score": 0.2876821, "_type": "test-type", "_id": "42", "_index": "test-index", "_source": { "any": "data", "timestamp": "2017-09-05T15:01:54.780318" } } ], "max_score": 0.2876821, "total": 1 }, "timed_out": false, "_shards": { "failed": 0, "total": 5, "successful": 5 }, "took": 6 } """

Elasticsearch Python API