创建索引、插入数据
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 } """