elasticsearch6.5.4搜索(1.简单查询)
查询索引library中book类型的title字段中含有crime一词的文档
1.使用postman
url:http://localhost:9002/library/book/_search?pretty=true
结果:
2.python 查询
# -*- coding: utf-8 -*-
import json
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk
ES_HOST = '127.0.0.1'
ES_USER = ''
ES_PASSWD = ''
ES_PORT = 9002
class ES():
def __init__(self):
self.es = Elasticsearch([ES_HOST], port=ES_PORT, timeout=300)
# def create_index(self, index): 参见上篇博文
# def insert_bulk(self, data_list): 参见上篇博文
def search_data(self, index, doc_type, query):
"""
查询数据
:param self:
:param query: 查询条件
:return:
"""
rtn = self.es.search(index=index, doc_type=doc_type, scroll='5m', body=json.dumps(query), request_timeout=300)
return rtn
if __name__ == '__main__':
es = ES()
print '---------'
# 查询数据
index = 'library'
doc_type = 'book'
query = {
"min_score":0.5, # 根据查询结果匹配度得分获取数据,分值越高,数据的匹配度越高。此处查询大于等于0.5的数据
"version": True, # 返回版本信息
"size": 2, # 返回2条数据
"query": {"query_string": {"query": "title:crime"}}, # 查询条件
"_source": ["author", "tags", "title", "year"], # 返回指定字段
"script_fields" : { # 使用脚本字段,获取year字段值进行计算,计算结果赋值给新增字段correctYear
"correctYear" : {
"script" : "doc['year'].value - 1000"
}
}
}
print es.search_data(index, doc_type, query)
print '---------'