es_client.py
1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""Elasticsearch向量数据库客户端实现."""
from typing import Any, Dict, List, Optional
from app.core.config import settings
from app.db.base import VectorDBClient
class ElasticsearchClient(VectorDBClient):
"""Elasticsearch向量数据库客户端.
使用Elasticsearch的dense_vector类型存储向量,支持向量相似度搜索。
"""
def __init__(self, es_url: Optional[str] = None):
"""初始化ES客户端.
Args:
es_url: Elasticsearch连接URL,默认从配置读取
"""
self.es_url = es_url or settings.get("db_es_url", "http://localhost:9200")
self._client: Optional[Any] = None
async def connect(self) -> None:
"""建立ES连接."""
from elasticsearch import AsyncElasticsearch
self._client = AsyncElasticsearch([self.es_url])
# 验证连接
await self._client.ping()
async def disconnect(self) -> None:
"""断开ES连接."""
if self._client:
await self._client.close()
self._client = None
async def health_check(self) -> bool:
"""检查ES连接健康状态."""
if not self._client:
return False
try:
return await self._client.ping()
except Exception:
return False
_es_client: Optional[ElasticsearchClient] = None
def get_es_client() -> ElasticsearchClient:
"""获取全局ES客户端实例(单例模式).
Returns:
ElasticsearchClient: ES客户端实例
"""
global _es_client
if _es_client is None:
_es_client = ElasticsearchClient()
return _es_client