安装模块
pip install elasticsearch
创建连接
from elasticsearch import Elasticsearch es = Elasticsearch(['192.168.1.1:9200']) |
多节点
es = Elasticsearch(['192.168.1.1:9200',’192.168.1.2:9200’]) |
支持 SSL 的连接
es = Elasticsearch( ['localhost:443', 'other_host:443'], # turn on SSL use_ssl=True, # make sure we verify SSL certificates (off by default) verify_certs=True, # provide a path to CA certs on disk ca_certs='/path/to/CA_certs' ) |
创建索引
es . indices . create ( index = 'test_index' , ignore = 400 ) es.indices.delete(index='test_index', ignore=[400, 404]) |
ignore 可以忽略异常, 其值是需要忽略的异常对应的返回码, 常见的有 400 表示索引已存在, 404 表示索引没找到.
使用自定义映射创建索引:
mapping = { "mappings": { "test_type": { "properties": { "name": { "type": "string", "index": "not_analyzed" }, "phone": { "type": "string", "index": "not_analyzed" } } } } } es.indices.create(index='test_index',ignore=400,body=mapping) |
查看索引的映射:
es.indices.get_mapping("test_index") |
写入数据
插入一条:
es.index(index='test_index’,doc_type='test_type',body={“key”:”value”}) |
批量写入:
doc = [ {"index": {}}, {'name': 'Jack', 'phone': '123456'}, {"index": {}}, {'name': 'Joe', 'phone': '321456' }, {"index": {}}, {'name': 'Nicole', 'phone': '654321'}, {"index": {}}, {'name': 'Lucy', 'phone': '456123'}, ] es.bulk(index='test_index',doc_type='test_type',body=doc) |
删除数据
根据 id 删除一条数据
es.delete(index="test_index",doc_type="test_type",id="ZTg5IGMBxTpLs9ylvHBz") |
根据查询条件删除数据:
body = { "query":{ "match":{ "name": "Joe" } } } es.delete_by_query(index='test_index',doc_type='test_type',body=body) |
查询
查询所有数据
body = { "query":{ "match_all":{} } } es.search(index="test_index",doc_type="test_type",body=body) |
或者
es.search(index="test_index",doc_type="test_type") |
完全匹配 term:
# 搜索 name 字段为 Nicole 的数据 body = { "query":{ "term":{ "name": "Nicole" } } } es.search(index="test_index",doc_type="test_type",body=body) |
关键字匹配 match:
# 搜索 name 字段包含 Nicole 关键字的数据 body = { "query":{ "match":{ "name": "Nicole" } } } es.search(index="test_index",doc_type="test_type",body=body) |
bool 联合查询, bool 有 3 类查询关系, must(都满足),should(其中一个满足),must_not(都不满足)
# 搜索 name 为 Nicole 并且 phone 为 123456 的数据 body = { "query":{ "bool":{ "must":[ { "term":{ "name": "Nicole" } }, { "term":{ "phone": “123456” } } ] } } } es.search(index="test_index",doc_type="test_type",body=body) |
来源: http://www.bubuko.com/infodetail-2586080.html