46 lines
1.4 KiB
Python
46 lines
1.4 KiB
Python
|
import logging
|
|||
|
|
|||
|
from ElasticSearch.Utils.ElasticsearchConnectionPool import ElasticsearchConnectionPool
|
|||
|
|
|||
|
# 初始化日志
|
|||
|
logger = logging.getLogger(__name__)
|
|||
|
logger.setLevel(logging.INFO)
|
|||
|
|
|||
|
class EsSearchUtil:
|
|||
|
def __init__(self, es_config):
|
|||
|
"""
|
|||
|
初始化Elasticsearch搜索工具
|
|||
|
:param es_config: Elasticsearch配置字典,包含hosts, username, password, index_name等
|
|||
|
"""
|
|||
|
self.es_config = es_config
|
|||
|
|
|||
|
# 初始化连接池
|
|||
|
self.es_pool = ElasticsearchConnectionPool(
|
|||
|
hosts=es_config['hosts'],
|
|||
|
basic_auth=es_config['basic_auth'],
|
|||
|
verify_certs=es_config.get('verify_certs', False),
|
|||
|
max_connections=50
|
|||
|
)
|
|||
|
|
|||
|
self.index_name = es_config['index_name']
|
|||
|
logger.info(f"EsSearchUtil初始化成功,索引名称: {self.index_name}")
|
|||
|
|
|||
|
def text_search(self, query, size=10):
|
|||
|
# 从连接池获取连接
|
|||
|
conn = self.es_pool.get_connection()
|
|||
|
try:
|
|||
|
# 使用连接执行搜索
|
|||
|
result = conn.search(
|
|||
|
index=self.es_config['index_name'],
|
|||
|
query={"match": {"user_input": query}},
|
|||
|
size=size
|
|||
|
)
|
|||
|
return result
|
|||
|
except Exception as e:
|
|||
|
logger.error(f"文本搜索失败: {str(e)}")
|
|||
|
raise
|
|||
|
finally:
|
|||
|
# 释放连接回连接池
|
|||
|
self.es_pool.release_connection(conn)
|
|||
|
|