ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。
1建立关联
首先需要安装elasticsearch库,pip install elasticsearch
from elasticsearch import Elasticsearch
from datetime import datetime
es = Elasticsearch()
#默认连接本地的ES服务
#如果要连接其它地址的ES可以把传入地址
#es = Elasticsearch('127.0.0.1:9200')
就这样我们就可以对ES进行操作了
2创建索引
answer_index = 'baidu_answer'
answer_type = 'doc'
answer_mapping = {
"doc": {
"properties": {
"qtitle": {
"type": "text",
# "index": True
},
"rContent": {
"type": "text",
# "analyzer": "ik_max_word"
}
}
}
}
# 创建索引
es.indices.create(answer_index)
# 设置mapping
es.indices.put_mapping(index=answer_index,doc_type=answer_type,body=answer_mapping)
这样操作比较规范,也可以不设置mapping,ES会根据你传入的值自动设置属性,但有可能会带来小问题。
- 其它操作
# # 查看所有索引
# alias = es.indices.get_alias()
# print(alias)
#
# # 查询所有index名称
# result = es.indices.get_alias().keys()
# print(result)
#
# # 查询index信息,包含mapping settings信息
# result = es.indices.get(index_name)
# print(result)
#
# # 查看指定index的mapping信息
# result = es.indices.get_mapping(index_name)
# print(result)
#
# # 查看指定index的mapping信息
# result = es.indices.get_settings(index_name)
# print(result)
插入数据
索引创建后就可以往ES插入数据了
- 单条插入或更新数据
# 插入或更新数据
doc = {'id': 7, 'schoolId': '007', 'schoolName': '大明1'}
es.index(index=answer_index ,doc_type=answer_type ,body=doc, id=doc['id'])
es.index(index=answer_index ,doc_type=answer_type ,body=doc, id=1)
es.index(index=answer_index ,doc_type=answer_type ,body=doc, id=12)
- 更新数据
es.update(index='indexName', doc_type='typeName', id='idValue', body={待更新字段})
- 批量插入数据
from elasticsearch import helpers
#批量插入数据
actions = []
i = 0
f = open(answers.txt','r',encoding='utf8')
for j in f:
action = {
"_index":answer_index,
'_type':answer_type,
'_id':i,
'_source':j,
}
i+=1
actions.append(action)
helpers.bulk(es,actions)
注意使用批量插入要导入helpers
搜索数据
- 根据id查找数据
res = es.get(index='test-index',doc_type='test_type',id=1)
print(res)
- 搜索数据
match:在qtitle中包含年收入的都会被搜索出来
ids:根据id值
res = es.search(index='test-index',body={'query':{'match':{'qtitle':' 年收入'}}})
# res = es.search(index='test-index',body={'query':{'ids':{'values':'1'}}})
# print(res)
result = res['hits']['hits']
# print(result)
for r in result:
print(r['_id'])
print(r['_source'])
删除
delete:删除指定index、type、id的文档
es.delete(index='indexName', doc_type='typeName', id='idValue')