当前位置:首页 > 日记本 > 正文内容

python下elasticsearch搜索接口封装实现

zhangchap3年前 (2021-09-11)日记本278
# -*- coding:utf-8 -*-
from elasticsearch import Elasticsearch,TransportError
from typing import Any

def search(es:Elasticsearch,index:Any,word:str,size:int = 10):
   try:
      result = es.search(index=index,q=word,size=size,ignore=[400,401,403,409])
   except TransportError as e:
      print(f'搜索{word}出错:{e.error}')
      return None,0
   try:
      hits = result['hits']['hits']
      total = result['hits']['total']['value']
      # 以下代码可以用列表推导式实现
      # result_items = []
      # for item in hits:
      #  source = item['_source']
      #  title = item['_source']['title']
      #  content = item['_source']['content']
      #  score = item['_score']
      #  result_items.append(title)
   except KeyError:
      return None,0
   return [item['_source'] for item in hits],total


if __name__ == '__main__':
   es_client = Elasticsearch()
   index_name = 'test-demo0'
   keyword = '互联网'
   items,count = search(es_client,index_name,keyword,20)
   print(count)


标签: elasticsearch
分享给朋友:

相关文章

elasticsearch安装步骤及运行

elasticsearch安装步骤及运行

下载链接:https://www.elastic.co/cn/downloads/elasticsearch虽然服务器是国外的,但是下载速度很快解压到D盘根目录,避免兼容性,不要有中文的路径打开bin...

elasticsearch 127.0.0.1:9200 连接被重置

之前安装过7.0的版本没有问题,现在用最新版的8.3.2的版本,启动后访问 9200端口提示连接被重置一下是解决方案:config目录中的elasticsearch.yml将xpack.securit...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。