python下使用ElasticSearch

一 什么是 ElasticSearch

Elasticsearch 是一个分布式可扩展的实时搜索和分析引擎,一个建立在全文搜索引擎 Apache Lucene(TM) 基础上的搜索引擎.当然 Elasticsearch 并不仅仅是 Lucene 那么简单,它不仅包括了全文搜索功能,还可以进行以下工作:

  • 分布式实时文件存储,并将每一个字段都编入索引,使其可以被搜索。
  • 可实现亿级数据实时查询
  • 实时分析的分布式搜索引擎。
  • 可以扩展到上百台服务器,处理PB级别的结构化或非结构化数据。

二 安装(windows下)

安装包下载地址

注意:Elasticsearch是用Java开发的,最新版本的Elasticsearch需要安装jdk1.8以上的环境

安装包下载完,解压,进入到bin目录,启动 elasticsearch.bat 即可

三 python操作ElasticSearch

from elasticsearch import Elasticsearch

# 创建ES对象
obj=Elasticsearch()
# 创建索引index:索引的名字,body:数据,ignore:状态码
result=obj.indices.create(index="user",body={"userid":"1","username":"maple"},ignore=400)

print(result)
# {'error': {'root_cause': [{'type': 'parse_exception', 'reason': 'unknown key [userid] for create index'}], 'type': 'parse_exception', 'reason': 'unknown key [userid] for create index'}, 'status': 400}
# 删除索引
result = obj.indices.delete(index='user', ignore=[400, 404])

result = obj.delete(index='news', doc_type='politics', id=1)
# 插入数据
data={"userid":"1","username":"maple","password":"123"}
# index:索引名字,id:文档ID,doc_type:文档类型,body:数据
result=obj.create(index="news",doc_type="politics", id=1, body=data)
# {'_index': 'news', '_type': 'politics', '_id': '1', '_version': 1, 'result': 'created', '_shards': {'total': 2, 'successful': 1, 'failed': 0}, '_seq_no': 0, '_primary_term': 1}
print(result)

# 更新数据
'''
不用doc包裹会报错
ActionRequestValidationException[Validation Failed: 1: script or doc is missing
'''
data ={"doc":{"userid": "1", "username": "maple","password":"123456","test":"测试"}}
result = obj.update(index="news", doc_type="politics", body=data, id=1)
# {'_index': 'news', '_type': 'politics', '_id': '1', '_version': 7, 'result': 'updated', '_shards': {'total': 2, 'successful': 1, 'failed': 0}, '_seq_no': 6, '_primary_term': 1}
print(result)

# 查询所有文档
query={"query":{"match_all":{}}}
# 查找名字叫maple的所有文档
# query = {'query': {'term': {'username': 'maple'}}}
# 查找年龄大于11的所有文档
# query = {'query': {'range': {'age': {'gt': 11}}}}
all_doc=obj.search(index="news", body=query)
# {'userid': '1', 'username': 'maple', 'password': '123456', 'test': '测试'}
print(all_doc["hits"]["hits"][0]["_source"])
原文地址:https://www.cnblogs.com/angelyan/p/10798594.html