您的位置:首页 > 编程语言 > Python开发

elasticsearch API使用方法备忘(Python)

2018-05-03 17:39 816 查看

安装模块

pipinstallelasticsearch

创建连接

fromelasticsearchimportElasticsearch
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'],#turnonSSLuse_ssl=True,#makesureweverifySSLcertificates(offbydefault)verify_certs=True,#provideapathtoCAcertsondiskca_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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  elasticsearch api pytho