Flask项目中实现搜索
-
python中使用elasticsearch
-
安装
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}} ] } } } # index:库名,doc_typ:表名 类型, body:查询条件 字典 ret = es.search(index='articles', doc_type='article', body=query) print(ret['hits']['hits'])
-
-
suggest建议查询(实现户业务:没完全输入完成的情况,可以做自动补全提升)
-
拼写纠错
# 当我们输入错误的关键词phtyon web时,es可以提供根据索引库数据得出的正确拼写python web 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 } } } }' # word-phrase表示返回来的数据放在word-phrase中。 # phrase表示以短语的方式返回,field指定从哪里获取数据,size指定返回一条数据。
-
自动补全
自动补全需要用到suggest查询建议中的type=completion,所以原先建立的文章索引库不能用于自动补全,需要再建立一个自动补全的索引库
-
创建自动补全的索引库
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/_mapping/words -H 'Content-Type: application/json' -d' { "words": { "properties": { "suggest": { "type": "completion", "analyzer": "ik_max_word" } } } }' # 自动补全建议,必须是completion类型。
-
使用logstash导入自动补全初始数据
# 创建脚本: vim /home/python/logstash_mysql_completion.conf # 脚本内容: input{ jdbc { jdbc_driver_library => "/home/python/mysql-connector-java-8.0.13/mysql-connector-java-8.0.13.jar" jdbc_driver_class => "com.mysql.jdbc.Driver" jdbc_connection_string => "jdbc:mysql://127.0.0.1:3306/toutiao?tinyInt1isBit=false" jdbc_user => "root" jdbc_password => "mysql" jdbc_paging_enabled => "true" jdbc_page_size
-
-