安装 pip install elasticsearch
对于elasticsearch 5.x 版本 需要按以下方式导入
from elasticsearch5 import Elasticsearch
# elasticsearch集群服务器的地址
ES = [
'127.0.0.1:9200'
]
# 创建elasticsearch客户端
es = Elasticsearch(
ES,
# 启动前嗅探es集群服务器
sniff_on_start=True,
# es集群服务器结点连接异常时是否刷新es结点信息
sniff_on_connection_fail=True,
# 每60秒刷新结点信息
sniffer_timeout=60
)
搜索使用方式
query = {
'query': {
'bool': {
'must': [
{'match': {'_all': 'python web'}}
],
'filter': [
{'term': {'status': 2}}
]
}
}
}
ret = es.search(index='articles', doc_type='article', body=query)
suggest查询
1 拼写纠错
对于已经建立的articles索引库,elasticsearch还提供了一种查询模式,suggest建议查询模式
curl 127.0.0.1:9200/articles/article/_search?pretty -d '
{
"from": 0,
"size": 10,
"_source": false,
"suggest": {
"text": "phtyon web",
"word-phrase": {
"phrase": {
"field": "_all",
"size": 1
}
}
}
}'
当我们输入错误的关键词phtyon web时,es可以提供根据索引库数据得出的正确拼写python web
2 自动补全
使用elasticsearch提供的自动补全功能,因为文档的类型映射要特殊设置,所以原先建立的文章索引库不能用于自动补全,需要再建立一个自动补全的索引库
curl -X PUT 127.0.0.1:9200/completions -H 'Content-Type: application/json' -d'
{
"settings" : {
"index": {
"number_of_shards" : 3,
"number_of_replicas" : 1
}
}
}
curl -X PUT 127.0.0.1:9200/completions -H 'Content-Type: application/json' -d'
{
"settings" : {
"index": {
"number_of_shards" : 3,
"number_of_replicas" : 1
}
}
}
很简答理解:elasticsearch提供了两个建议查询,比如我想搜索python 结果我输入成了pyhton,elasticsearch会帮我们纠正,还有一种自动补全,比如我输入:python we 会帮我自动匹配,显而易见我想找python web