ITPub博客

首页 > IT基础架构 > > python操作Elasticsearch样例

python操作Elasticsearch样例

作者:飘絮絮絮丶 时间:2022-01-30 14:30:57 0 删除 编辑

本例目的仅仅是防止自己遗忘,如果能为一些朋友提供帮助,也是功德一件~

# coding=utf8

from datetime import datetime
from elasticsearch import Elasticsearch, RequestsHttpConnection

# 连接elasticsearch,默认是9200
es = Elasticsearch(
hosts=[
{'host': '127.0.0.1',
'port': 443}
],
use_ssl=True,
verify_certs=True,
connection_class=RequestsHttpConnection
)

# 创建索引,索引的名字是my-index,如果已经存在了,就返回个400,
# 这个索引可以现在创建,也可以在后面插入数据的时候再临时创建
# es.indices.create(index='my-index')
# {u'acknowledged':True}

doc = {
'author': 'kimchy',
'text': 'Elasticsearch: cool. bonsai cool.',
'timestamp': datetime.now(),
}
# 插入数据,(这里省略插入其他两条数据,后面用)
es.index(index="my-index", doc_type="test-type", id=01, body={"any": "data01", "timestamp": datetime.now()})
# {u'_type':u'test-type',u'created':True,u'_shards':{u'successful':1,u'failed':,u'total':2},u'_version':1,u'_index':u'my-index',u'_id':u'1}
# 也可以,在插入数据的时候再创建索引test-index
es.index(index="test-index", doc_type="test-type", id=42, body={"any": "data", "timestamp": datetime.now()})

# 查询数据,两种get and search
# get获取
res = es.get(index="my-index", doc_type="test-type", id=01)
print(res)
print(res['_source'])

# search获取
res = es.search(index="test-index", body={"query": {"match_all": {}}})
print(res)
for hit in res['hits']['hits']:
print(hit["_source"])
res = es.search(index="test-index", body={'query':{'match':{'any':'data'}}}) #获取any=data的所有值
print(res)


作者:BlueCat2016
链接:https://www.jianshu.com/p/ac3460c32b92
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69946831/viewspace-3127292/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-09-09

  • 博文量
    2646
  • 访问量
    42393