发布时间:2019-09-11 07:43:11编辑:auto阅读(2069)
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) | 
上一篇: Python之读取TXT文件的三种方法
下一篇: 学习python:练习5.简单红包程序
 51140
 50544
 41160
 37998
 32461
 29364
 28232
 23080
 23048
 21370
 1416°
 2114°
 1756°
 1679°
 1979°
 1758°
 2433°
 4100°
 3968°
 2835°