Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

feat(search): 添加 Elasticsearch 搜索引擎支持

JayLiu9785428ce929
diff --git a/docs/elasticsearch_search_engine.md b/docs/elasticsearch_search_engine.md
new file mode 100644
index 0000000000..581f9db2ac
--- /dev/null
+++ b/docs/elasticsearch_search_engine.md
@@ -0,0 +1,154 @@
+# Elasticsearch 搜索引擎
+
+这个文档介绍如何在 Local Deep Research 项目中使用和配置 Elasticsearch 搜索引擎。
+
+## 概述
+
+Elasticsearch 搜索引擎允许你搜索 Elasticsearch 索引中的文档。这对于需要搜索大量结构化或非结构化文本数据的场景非常有用。
+
+## 前提条件
+
+1. 运行中的 Elasticsearch 服务器(本地或远程)
+2. Elasticsearch Python 客户端库:`elasticsearch>=8.10.0`
+
+## 安装
+
+确保你已经安装了 `elasticsearch` Python 包。如果你是从源代码安装 Local Deep Research,可以运行:
+
+```bash
+pip install elasticsearch>=8.10.0
+```
+
+## 基本用法
+
+### 在代码中使用
+
+```python
+from local_deep_research.web_search_engines.engines.search_engine_elasticsearch import ElasticsearchSearchEngine
+
+# 创建搜索引擎实例
+es_search = ElasticsearchSearchEngine(
+ hosts=["http://localhost:9200"], # Elasticsearch 服务器地址
+ index_name="my_index", # 要搜索的索引名称
+ username="user", # 可选:认证用户名
+ password="pass", # 可选:认证密码
+ max_results=10 # 返回结果数量
+)
+
+# 执行搜索
+results = es_search.run("你的搜索查询")
+
+# 处理结果
+for result in results:
+ print(f"标题: {result.get('title')}")
+ print(f"片段: {result.get('snippet')}")
+ print(f"内容: {result.get('content')}")
+```
+
+### 高级搜索
+
+ES搜索引擎支持多种高级搜索方式:
+
+```python
+# 使用 Elasticsearch 查询字符串语法
+results = es_search.search_by_query_string("title:关键词 AND content:内容")
+
+# 使用 Elasticsearch DSL(领域特定语言)
+results = es_search.search_by_dsl({
+ "query": {
+ "bool": {
+ "must": {"match": {"content": "搜索词"}},
+ "filter": {"term": {"category": "技术"}}
+ }
+ }
+})
+```
+
+## 配置说明
+
+### 搜索引擎参数
+
+| 参数 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| hosts | List[str] | ["http://localhost:9200"] | Elasticsearch 服务器地址列表 |
+| index_name | str | "documents" | 要搜索的索引名称 |
+| username | Optional[str] | None | 认证用户名 |
+| password | Optional[str] | None | 认证密码 |
+| api_key | Optional[str] | None | API 密钥认证 |
+| cloud_id | Optional[str] | None | Elastic Cloud ID |
+| max_results | int | 10 | 最大结果数 |
+| highlight_fields | List[str] | ["content", "title"] | 要高亮显示的字段 |
+| search_fields | List[str] | ["content", "title"] | 要搜索的字段 |
+| filter_query | Optional[Dict] | None | 可选的过滤查询 |
+| llm | Optional[BaseLLM] | None | 用于相关性过滤的语言模型 |
+| max_filtered_results | Optional[int] | None | 过滤后的最大结果数 |
+
+## 索引数据
+
+为了便于使用,我们提供了 `ElasticsearchManager` 工具类来帮助索引数据:
+
+```python
+from local_deep_research.utilities.es_utils import ElasticsearchManager
+
+# 创建 ES 管理器
+es_manager = ElasticsearchManager(
+ hosts=["http://localhost:9200"]
+)
+
+# 创建索引
+es_manager.create_index("my_index")
+
+# 索引单个文档
+es_manager.index_document(
+ index_name="my_index",
+ document={
+ "title": "文档标题",
+ "content": "文档内容...",
+ }
+)
+
+# 批量索引文档
+documents = [
+ {"title": "文档1", "content": "内容1"},
+ {"title": "文档2", "content": "内容2"}
+]
+es_manager.bulk_index_documents("my_index", documents)
+
+# 索引文件(自动提取内容)
+es_manager.index_file("my_index", "path/to/document.pdf")
+
+# 索引整个目录中的文件
+es_manager.index_directory(
+ "my_index",
+ "path/to/docs",
+ file_patterns=["*.pdf", "*.docx", "*.txt"]
+)
+```
+
+## 示例
+
+查看 `examples/elasticsearch_search_example.py` 获取完整的使用示例。
+
+## 运行示例
+
+确保 Elasticsearch 正在运行,然后执行:
+
+```bash
+python examples/elasticsearch_search_example.py
+```
+
+## 故障排除
+
+### 无法连接到 Elasticsearch
+
+- 确保 Elasticsearch 服务器正在运行
+- 检查主机地址和端口是否正确
+- 验证认证凭据(如果需要)
+- 检查网络连接和防火墙设置
+
+### 搜索结果为空
+
+- 确保索引存在并且包含数据
+- 检查搜索字段是否正确
+- 尝试使用更简单的查询
+- 检查 Elasticsearch 日志获取更多信息
\ No newline at end of file
diff --git a/examples/elasticsearch_search_example.py b/examples/elasticsearch_search_example.py
new file mode 100644
index 0000000000..1c176d5c0e
--- /dev/null
+++ b/examples/elasticsearch_search_example.py
@@ -0,0 +1,174 @@
+"""
+使用 Elasticsearch 搜索引擎的示例脚本。
+展示如何索引文档和搜索数据。
+"""
+
+import logging
+import sys
+from pathlib import Path
+
+# 添加项目根目录到 Python 路径
+sys.path.append(str(Path(__file__).parent.parent))
+
+from src.local_deep_research.utilities.es_utils import ElasticsearchManager
+from src.local_deep_research.web_search_engines.engines.search_engine_elasticsearch import (
+ ElasticsearchSearchEngine,
+)
+
+# 配置日志
+logging.basicConfig(
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
+)
+logger = logging.getLogger(__name__)
+
+
+def index_sample_documents():
+ """索引示例文档到 Elasticsearch。"""
+
+ # 创建 Elasticsearch 管理器
+ es_manager = ElasticsearchManager(
+ hosts=["http://172.16.4.131:9200"],
+ # 如果需要可以提供认证信息
+ # username="elastic",
+ # password="password",
+ )
+
+ # 创建索引
+ index_name = "sample_documents"
+ es_manager.create_index(index_name)
+
+ # 准备示例文档
+ documents = [
+ {
+ "title": "Elasticsearch 简介",
+ "content": "Elasticsearch 是一个分布式、开源的搜索和分析引擎,适用于所有类型的数据。",
+ "tags": ["搜索引擎", "数据库", "全文搜索"],
+ "category": "技术",
+ },
+ {
+ "title": "Python 编程基础",
+ "content": "Python 是一种解释型、高级、通用型编程语言。Python 的设计强调代码的可读性,使用缩进表示代码块。",
+ "tags": ["编程语言", "脚本语言", "开发"],
+ "category": "编程",
+ },
+ {
+ "title": "自然语言处理介绍",
+ "content": "自然语言处理(NLP)是人工智能的一个子领域,专注于计算机与人类语言之间的交互。",
+ "tags": ["NLP", "AI", "机器学习"],
+ "category": "人工智能",
+ },
+ {
+ "title": "深度学习基础知识",
+ "content": "深度学习是机器学习的一个分支,它使用多层神经网络来模拟人脑的学习过程。",
+ "tags": ["深度学习", "神经网络", "AI"],
+ "category": "人工智能",
+ },
+ {
+ "title": "向量数据库比较",
+ "content": "向量数据库是专门为存储和检索高维向量而设计的数据库。常见的向量数据库包括Elasticsearch、Pinecone、Milvus等。",
+ "tags": ["向量数据库", "embeddings", "相似性搜索"],
+ "category": "数据库",
+ },
+ ]
+
+ # 批量索引文档
+ success_count = es_manager.bulk_index_documents(
+ index_name=index_name,
+ documents=documents,
+ refresh=True, # 立即刷新索引使文档可搜索
+ )
+
+ logger.info(f"成功索引了 {success_count} 个文档到 '{index_name}' 索引")
+ return index_name
+
+
+def search_documents(index_name, query):
+ """使用 Elasticsearch 搜索引擎搜索文档。"""
+
+ # 创建 Elasticsearch 搜索引擎
+ search_engine = ElasticsearchSearchEngine(
+ hosts=["http://172.16.4.131:9200"],
+ index_name=index_name,
+ max_results=10,
+ # 如果需要可以提供认证信息
+ # username="elastic",
+ # password="password",
+ )
+
+ # 执行搜索
+ logger.info(f"搜索查询: '{query}'")
+ results = search_engine.run(query)
+
+ # 显示搜索结果
+ logger.info(f"找到 {len(results)} 个结果:")
+ for i, result in enumerate(results, 1):
+ print(f"\n结果 {i}:")
+ print(f"标题: {result.get('title', '无标题')}")
+ print(f"片段: {result.get('snippet', '无摘要')[:100]}...")
+ if "score" in result:
+ print(f"相关性分数: {result.get('score')}")
+ print("-" * 50)
+
+ return results
+
+
+def advanced_search_examples(index_name):
+ """展示高级搜索功能的示例。"""
+
+ # 创建 Elasticsearch 搜索引擎
+ search_engine = ElasticsearchSearchEngine(
+ hosts=["http://172.16.4.131:9200"],
+ index_name=index_name,
+ )
+
+ # 1. 使用查询字符串语法
+ print("\n=== 使用查询字符串语法 ===")
+ query_string = "content:深度学习 OR title:elasticsearch"
+ print(f"查询字符串: '{query_string}'")
+ results = search_engine.search_by_query_string(query_string)
+ print(f"找到 {len(results)} 个结果")
+
+ # 2. 使用 DSL 查询
+ print("\n=== 使用 DSL 查询 ===")
+ query_dsl = {
+ "query": {
+ "bool": {
+ "must": {
+ "match": {
+ "content": "人工智能"
+ }
+ },
+ "filter": {
+ "term": {
+ "category.keyword": "人工智能"
+ }
+ }
+ }
+ }
+ }
+ print(f"DSL 查询: {query_dsl}")
+ results = search_engine.search_by_dsl(query_dsl)
+ print(f"找到 {len(results)} 个结果")
+
+
+def main():
+ """主函数,运行示例。"""
+ try:
+ # 索引示例文档
+ index_name = index_sample_documents()
+
+ # 执行基本搜索
+ search_documents(index_name, "elasticsearch")
+ search_documents(index_name, "深度学习")
+
+ # 展示高级搜索功能
+ advanced_search_examples(index_name)
+
+ except Exception as e:
+ logger.error(f"运行示例时出错: {str(e)}")
+ logger.error("请确保 Elasticsearch 正在运行,默认地址为 http://localhost:9200")
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/pdm.lock b/pdm.lock
index ad1bc0f62b..1afbf83e80 100644
--- a/pdm.lock
+++ b/pdm.lock
@@ -5,7 +5,7 @@
groups = ["default", "dev"]
strategy = ["inherit_metadata"]
lock_version = "4.5.0"
-content_hash = "sha256:ccb1dc4388f39bdc10f850a637801c0ddb96514150e9917fd738b2799b260649"
+content_hash = "sha256:afc18d1a41bc593825342aa394106ef3b085e3bd94c91ae36b1b1f0177f426e2"
[[metadata.targets]]
requires_python = ">=3.10"
@@ -135,7 +135,7 @@ name = "annotated-types"
version = "0.7.0"
requires_python = ">=3.8"
summary = "Reusable constraint types to use with typing.Annotated"
-groups = ["default", "dev"]
+groups = ["default"]
dependencies = [
"typing-extensions>=4.0.0; python_version < \"3.9\"",
]
@@ -434,7 +434,7 @@ name = "blinker"
version = "1.9.0"
requires_python = ">=3.9"
summary = "Fast, simple object-to-object and broadcast signaling"
-groups = ["default", "dev"]
+groups = ["default"]
files = [
{file = "blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc"},
{file = "blinker-1.9.0.tar.gz", hash = "sha256:b4ce2265a7abece45e7cc896e98dbebe6cead56bcf805a3d23136d145f5445bf"},
@@ -747,20 +747,6 @@ files = [
{file = "defusedxml-0.7.1.tar.gz", hash = "sha256:1bb3032db185915b62d7c6209c5a8792be6a32ab2fedacc84e01b52c51aa3e69"},
]
-[[package]]
-name = "dep-logic"
-version = "0.5.0"
-requires_python = ">=3.8"
-summary = "Python dependency specifications supporting logical operations"
-groups = ["dev"]
-dependencies = [
- "packaging>=22",
-]
-files = [
- {file = "dep_logic-0.5.0-py3-none-any.whl", hash = "sha256:f16a73ec5baf1f126e253f6a6249c80999818e608f84677736591ac623c516a6"},
- {file = "dep_logic-0.5.0.tar.gz", hash = "sha256:be92e772f15d2563edd6b8694a6818846ad2822310dfc8f39cd20ebb0b03e329"},
-]
-
[[package]]
name = "distlib"
version = "0.3.9"
@@ -809,6 +795,35 @@ files = [
{file = "dynaconf-3.2.10.tar.gz", hash = "sha256:8dbeef31a2343c8342c9b679772c3d005b4801c587cf2f525f98f57ec2f607f1"},
]
+[[package]]
+name = "elastic-transport"
+version = "8.17.1"
+requires_python = ">=3.8"
+summary = "Transport classes and utilities shared among Python Elastic client libraries"
+groups = ["default"]
+dependencies = [
+ "certifi",
+ "urllib3<3,>=1.26.2",
+]
+files = [
+ {file = "elastic_transport-8.17.1-py3-none-any.whl", hash = "sha256:192718f498f1d10c5e9aa8b9cf32aed405e469a7f0e9d6a8923431dbb2c59fb8"},
+ {file = "elastic_transport-8.17.1.tar.gz", hash = "sha256:5edef32ac864dca8e2f0a613ef63491ee8d6b8cfb52881fa7313ba9290cac6d2"},
+]
+
+[[package]]
+name = "elasticsearch"
+version = "8.14.0"
+requires_python = ">=3.7"
+summary = "Python client for Elasticsearch"
+groups = ["default"]
+dependencies = [
+ "elastic-transport<9,>=8.13",
+]
+files = [
+ {file = "elasticsearch-8.14.0-py3-none-any.whl", hash = "sha256:cef8ef70a81af027f3da74a4f7d9296b390c636903088439087b8262a468c130"},
+ {file = "elasticsearch-8.14.0.tar.gz", hash = "sha256:aa2490029dd96f4015b333c1827aa21fd6c0a4d223b00dfb0fe933b8d09a511b"},
+]
+
[[package]]
name = "emoji"
version = "2.14.1"
@@ -936,20 +951,6 @@ files = [
{file = "filetype-1.2.0.tar.gz", hash = "sha256:66b56cd6474bf41d8c54660347d37afcc3f7d1970648de365c102ef77548aadb"},
]
-[[package]]
-name = "findpython"
-version = "0.6.3"
-requires_python = ">=3.8"
-summary = "A utility to find python versions on your system"
-groups = ["dev"]
-dependencies = [
- "packaging>=20",
-]
-files = [
- {file = "findpython-0.6.3-py3-none-any.whl", hash = "sha256:a85bb589b559cdf1b87227cc233736eb7cad894b9e68021ee498850611939ebc"},
- {file = "findpython-0.6.3.tar.gz", hash = "sha256:5863ea55556d8aadc693481a14ac4f3624952719efc1c5591abb0b4a9e965c94"},
-]
-
[[package]]
name = "flake8"
version = "7.1.2"
@@ -1207,20 +1208,6 @@ files = [
{file = "h11-0.14.0.tar.gz", hash = "sha256:8f19fbbe99e72420ff35c00b27a34cb9937e902a8b810e2c88300c6f0a3b699d"},
]
-[[package]]
-name = "hishel"
-version = "0.1.2"
-requires_python = ">=3.9"
-summary = "Persistent cache implementation for httpx and httpcore"
-groups = ["dev"]
-dependencies = [
- "httpx>=0.28.0",
-]
-files = [
- {file = "hishel-0.1.2-py3-none-any.whl", hash = "sha256:802b4e446017f4867efdb26d3417670991ad1b4826d24331110871fe8957b5d0"},
- {file = "hishel-0.1.2.tar.gz", hash = "sha256:6643450bfb1cfa2ecd6002769f6f5069d0d048c9c1f1e29a98a48302d5875092"},
-]
-
[[package]]
name = "html5lib"
version = "1.1"
@@ -1279,22 +1266,6 @@ files = [
{file = "httpx_sse-0.4.0-py3-none-any.whl", hash = "sha256:f329af6eae57eaa2bdfd962b42524764af68075ea87370a2de920af5341e318f"},
]
-[[package]]
-name = "httpx"
-version = "0.28.1"
-extras = ["socks"]
-requires_python = ">=3.8"
-summary = "The next generation HTTP client."
-groups = ["dev"]
-dependencies = [
- "httpx==0.28.1",
- "socksio==1.*",
-]
-files = [
- {file = "httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad"},
- {file = "httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc"},
-]
-
[[package]]
name = "huggingface-hub"
version = "0.29.3"
@@ -1315,20 +1286,6 @@ files = [
{file = "huggingface_hub-0.29.3.tar.gz", hash = "sha256:64519a25716e0ba382ba2d3fb3ca082e7c7eb4a2fc634d200e8380006e0760e5"},
]
-[[package]]
-name = "id"
-version = "1.5.0"
-requires_python = ">=3.8"
-summary = "A tool for generating OIDC identities"
-groups = ["dev"]
-dependencies = [
- "requests",
-]
-files = [
- {file = "id-1.5.0-py3-none-any.whl", hash = "sha256:f1434e1cef91f2cbb8a4ec64663d5a23b9ed43ef44c4c957d02583d61714c658"},
- {file = "id-1.5.0.tar.gz", hash = "sha256:292cb8a49eacbbdbce97244f47a97b4c62540169c976552e497fd57df0734c1d"},
-]
-
[[package]]
name = "identify"
version = "2.6.9"
@@ -1365,17 +1322,6 @@ files = [
{file = "importlib_resources-6.5.2.tar.gz", hash = "sha256:185f87adef5bcc288449d98fb4fba07cea78bc036455dd44c5fc4a2fe78fed2c"},
]
-[[package]]
-name = "installer"
-version = "0.7.0"
-requires_python = ">=3.7"
-summary = "A library for installing Python wheels."
-groups = ["dev"]
-files = [
- {file = "installer-0.7.0-py3-none-any.whl", hash = "sha256:05d1933f0a5ba7d8d6296bb6d5018e7c94fa473ceb10cf198a92ccea19c27b53"},
- {file = "installer-0.7.0.tar.gz", hash = "sha256:a26d3e3116289bb08216e0d0f7d925fcef0b0194eedfa0c944bcaaa106c4b631"},
-]
-
[[package]]
name = "ipykernel"
version = "6.29.5"
@@ -2262,20 +2208,6 @@ files = [
{file = "lxml-5.3.1.tar.gz", hash = "sha256:106b7b5d2977b339f1e97efe2778e2ab20e99994cbb0ec5e55771ed0795920c8"},
]
-[[package]]
-name = "markdown-it-py"
-version = "3.0.0"
-requires_python = ">=3.8"
-summary = "Python port of markdown-it. Markdown parsing, done right!"
-groups = ["dev"]
-dependencies = [
- "mdurl~=0.1",
-]
-files = [
- {file = "markdown-it-py-3.0.0.tar.gz", hash = "sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb"},
- {file = "markdown_it_py-3.0.0-py3-none-any.whl", hash = "sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1"},
-]
-
[[package]]
name = "markupsafe"
version = "3.0.2"
@@ -2375,17 +2307,6 @@ files = [
{file = "mccabe-0.7.0.tar.gz", hash = "sha256:348e0240c33b60bbdf4e523192ef919f28cb2c3d7d5c7794f74009290f236325"},
]
-[[package]]
-name = "mdurl"
-version = "0.1.2"
-requires_python = ">=3.7"
-summary = "Markdown URL utilities"
-groups = ["dev"]
-files = [
- {file = "mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8"},
- {file = "mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba"},
-]
-
[[package]]
name = "mistune"
version = "3.1.3"
@@ -2411,60 +2332,6 @@ files = [
{file = "mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f"},
]
-[[package]]
-name = "msgpack"
-version = "1.1.0"
-requires_python = ">=3.8"
-summary = "MessagePack serializer"
-groups = ["dev"]
-files = [
- {file = "msgpack-1.1.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:7ad442d527a7e358a469faf43fda45aaf4ac3249c8310a82f0ccff9164e5dccd"},
- {file = "msgpack-1.1.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:74bed8f63f8f14d75eec75cf3d04ad581da6b914001b474a5d3cd3372c8cc27d"},
- {file = "msgpack-1.1.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:914571a2a5b4e7606997e169f64ce53a8b1e06f2cf2c3a7273aa106236d43dd5"},
- {file = "msgpack-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c921af52214dcbb75e6bdf6a661b23c3e6417f00c603dd2070bccb5c3ef499f5"},
- {file = "msgpack-1.1.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d8ce0b22b890be5d252de90d0e0d119f363012027cf256185fc3d474c44b1b9e"},
- {file = "msgpack-1.1.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:73322a6cc57fcee3c0c57c4463d828e9428275fb85a27aa2aa1a92fdc42afd7b"},
- {file = "msgpack-1.1.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:e1f3c3d21f7cf67bcf2da8e494d30a75e4cf60041d98b3f79875afb5b96f3a3f"},
- {file = "msgpack-1.1.0-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:64fc9068d701233effd61b19efb1485587560b66fe57b3e50d29c5d78e7fef68"},
- {file = "msgpack-1.1.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:42f754515e0f683f9c79210a5d1cad631ec3d06cea5172214d2176a42e67e19b"},
- {file = "msgpack-1.1.0-cp310-cp310-win32.whl", hash = "sha256:3df7e6b05571b3814361e8464f9304c42d2196808e0119f55d0d3e62cd5ea044"},
- {file = "msgpack-1.1.0-cp310-cp310-win_amd64.whl", hash = "sha256:685ec345eefc757a7c8af44a3032734a739f8c45d1b0ac45efc5d8977aa4720f"},
- {file = "msgpack-1.1.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:3d364a55082fb2a7416f6c63ae383fbd903adb5a6cf78c5b96cc6316dc1cedc7"},
- {file = "msgpack-1.1.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:79ec007767b9b56860e0372085f8504db5d06bd6a327a335449508bbee9648fa"},
- {file = "msgpack-1.1.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:6ad622bf7756d5a497d5b6836e7fc3752e2dd6f4c648e24b1803f6048596f701"},
- {file = "msgpack-1.1.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8e59bca908d9ca0de3dc8684f21ebf9a690fe47b6be93236eb40b99af28b6ea6"},
- {file = "msgpack-1.1.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5e1da8f11a3dd397f0a32c76165cf0c4eb95b31013a94f6ecc0b280c05c91b59"},
- {file = "msgpack-1.1.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:452aff037287acb1d70a804ffd022b21fa2bb7c46bee884dbc864cc9024128a0"},
- {file = "msgpack-1.1.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:8da4bf6d54ceed70e8861f833f83ce0814a2b72102e890cbdfe4b34764cdd66e"},
- {file = "msgpack-1.1.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:41c991beebf175faf352fb940bf2af9ad1fb77fd25f38d9142053914947cdbf6"},
- {file = "msgpack-1.1.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:a52a1f3a5af7ba1c9ace055b659189f6c669cf3657095b50f9602af3a3ba0fe5"},
- {file = "msgpack-1.1.0-cp311-cp311-win32.whl", hash = "sha256:58638690ebd0a06427c5fe1a227bb6b8b9fdc2bd07701bec13c2335c82131a88"},
- {file = "msgpack-1.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:fd2906780f25c8ed5d7b323379f6138524ba793428db5d0e9d226d3fa6aa1788"},
- {file = "msgpack-1.1.0-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:d46cf9e3705ea9485687aa4001a76e44748b609d260af21c4ceea7f2212a501d"},
- {file = "msgpack-1.1.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:5dbad74103df937e1325cc4bfeaf57713be0b4f15e1c2da43ccdd836393e2ea2"},
- {file = "msgpack-1.1.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:58dfc47f8b102da61e8949708b3eafc3504509a5728f8b4ddef84bd9e16ad420"},
- {file = "msgpack-1.1.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4676e5be1b472909b2ee6356ff425ebedf5142427842aa06b4dfd5117d1ca8a2"},
- {file = "msgpack-1.1.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:17fb65dd0bec285907f68b15734a993ad3fc94332b5bb21b0435846228de1f39"},
- {file = "msgpack-1.1.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a51abd48c6d8ac89e0cfd4fe177c61481aca2d5e7ba42044fd218cfd8ea9899f"},
- {file = "msgpack-1.1.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2137773500afa5494a61b1208619e3871f75f27b03bcfca7b3a7023284140247"},
- {file = "msgpack-1.1.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:398b713459fea610861c8a7b62a6fec1882759f308ae0795b5413ff6a160cf3c"},
- {file = "msgpack-1.1.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:06f5fd2f6bb2a7914922d935d3b8bb4a7fff3a9a91cfce6d06c13bc42bec975b"},
- {file = "msgpack-1.1.0-cp312-cp312-win32.whl", hash = "sha256:ad33e8400e4ec17ba782f7b9cf868977d867ed784a1f5f2ab46e7ba53b6e1e1b"},
- {file = "msgpack-1.1.0-cp312-cp312-win_amd64.whl", hash = "sha256:115a7af8ee9e8cddc10f87636767857e7e3717b7a2e97379dc2054712693e90f"},
- {file = "msgpack-1.1.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:071603e2f0771c45ad9bc65719291c568d4edf120b44eb36324dcb02a13bfddf"},
- {file = "msgpack-1.1.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0f92a83b84e7c0749e3f12821949d79485971f087604178026085f60ce109330"},
- {file = "msgpack-1.1.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:4a1964df7b81285d00a84da4e70cb1383f2e665e0f1f2a7027e683956d04b734"},
- {file = "msgpack-1.1.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:59caf6a4ed0d164055ccff8fe31eddc0ebc07cf7326a2aaa0dbf7a4001cd823e"},
- {file = "msgpack-1.1.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0907e1a7119b337971a689153665764adc34e89175f9a34793307d9def08e6ca"},
- {file = "msgpack-1.1.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:65553c9b6da8166e819a6aa90ad15288599b340f91d18f60b2061f402b9a4915"},
- {file = "msgpack-1.1.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:7a946a8992941fea80ed4beae6bff74ffd7ee129a90b4dd5cf9c476a30e9708d"},
- {file = "msgpack-1.1.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:4b51405e36e075193bc051315dbf29168d6141ae2500ba8cd80a522964e31434"},
- {file = "msgpack-1.1.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b4c01941fd2ff87c2a934ee6055bda4ed353a7846b8d4f341c428109e9fcde8c"},
- {file = "msgpack-1.1.0-cp313-cp313-win32.whl", hash = "sha256:7c9a35ce2c2573bada929e0b7b3576de647b0defbd25f5139dcdaba0ae35a4cc"},
- {file = "msgpack-1.1.0-cp313-cp313-win_amd64.whl", hash = "sha256:bce7d9e614a04d0883af0b3d4d501171fbfca038f12c77fa838d9f198147a23f"},
- {file = "msgpack-1.1.0.tar.gz", hash = "sha256:dd432ccc2c72b914e4cb77afce64aab761c1137cc698be3984eee260bcb2896e"},
-]
-
[[package]]
name = "multidict"
version = "6.2.0"
@@ -3122,17 +2989,6 @@ files = [
{file = "pathspec-0.12.1.tar.gz", hash = "sha256:a482d51503a1ab33b1c67a6c3813a26953dbdc71c31dacaef9a838c4e29f5712"},
]
-[[package]]
-name = "pbs-installer"
-version = "2025.4.9"
-requires_python = ">=3.8"
-summary = "Installer for Python Build Standalone"
-groups = ["dev"]
-files = [
- {file = "pbs_installer-2025.4.9-py3-none-any.whl", hash = "sha256:af110b398248584422f46760ce1e3793622fe3fbcde47aacd22e35baf8c3db1d"},
- {file = "pbs_installer-2025.4.9.tar.gz", hash = "sha256:15755bc94769a544af5dda155f973c70caf76f0e70b21f3c8a8ed506f102f88f"},
-]
-
[[package]]
name = "pdfminer-six"
version = "20250327"
@@ -3164,78 +3020,6 @@ files = [
{file = "pdfplumber-0.11.6.tar.gz", hash = "sha256:d0f419e031641d9eac70dc18c60e1fc3ca2ec28cce7e149644923c030a0003ff"},
]
-[[package]]
-name = "pdm"
-version = "2.24.1"
-requires_python = ">=3.9"
-summary = "A modern Python package and dependency manager supporting the latest PEP standards"
-groups = ["dev"]
-dependencies = [
- "blinker",
- "certifi>=2024.8.30",
- "dep-logic>=0.5",
- "filelock>=3.13",
- "findpython<1.0.0a0,>=0.6.0",
- "hishel>=0.0.32",
- "httpcore>=1.0.6",
- "httpx[socks]<1,>0.20",
- "id>=1.5.0",
- "importlib-metadata>=3.6; python_version < \"3.10\"",
- "installer<0.8,>=0.7",
- "msgpack>=1.0",
- "packaging!=22.0,>=20.9",
- "pbs-installer>=2024.4.18",
- "platformdirs",
- "pyproject-hooks",
- "python-dotenv>=0.15",
- "resolvelib>=1.1",
- "rich>=12.3.0",
- "shellingham>=1.3.2",
- "tomli>=1.1.0; python_version < \"3.11\"",
- "tomlkit<1,>=0.11.1",
- "truststore>=0.9; python_version >= \"3.10\"",
- "unearth>=0.17.5",
- "virtualenv>=20",
-]
-files = [
- {file = "pdm-2.24.1-py3-none-any.whl", hash = "sha256:4e496d6396de0633e011c33f971db08fc8f3b5b4c794163e4d867cf411960f16"},
- {file = "pdm-2.24.1.tar.gz", hash = "sha256:fc8adf011caa4ee2b0f25dabf890152aa4153cc21599ea67fe0c14e533dcd6d9"},
-]
-
-[[package]]
-name = "pdm-bump"
-version = "0.9.12"
-requires_python = ">=3.9"
-summary = "A plugin for PDM providing the ability to modify the version according to PEP440"
-groups = ["dev"]
-dependencies = [
- "annotated-types>=0.7.0",
- "pdm-pfsc>=0.12.3",
- "pdm>=2.22.4",
- "pyproject-metadata>=0.9.1",
- "tomli>=2.2.1; python_version <= \"3.10\"",
- "tomlkit>=0.13.2",
- "typing-extensions>=4.12.2; python_version <= \"3.9\"",
-]
-files = [
- {file = "pdm_bump-0.9.12-py3-none-any.whl", hash = "sha256:a830a0c234284d8eb04b0f5c53dc77b2bdee1329783040fab16edede40abe77c"},
- {file = "pdm_bump-0.9.12.tar.gz", hash = "sha256:057687574002d82747c9f02a013fc1cab34fcab35502f96af8efe5f6c79b12ca"},
-]
-
-[[package]]
-name = "pdm-pfsc"
-version = "0.12.3"
-requires_python = ">=3.9"
-summary = "Core functionPlug-In Foundation Service Collection)"
-groups = ["dev"]
-dependencies = [
- "pdm>=2.12.4",
- "pyproject-metadata>=0.7.1",
-]
-files = [
- {file = "pdm_pfsc-0.12.3-py3-none-any.whl", hash = "sha256:f1811cc8e80d3d4414a239f6d484daf1accca934448d7cbfd11d2b3698cd23fe"},
-]
-
[[package]]
name = "pexpect"
version = "4.9.0"
@@ -3755,32 +3539,6 @@ files = [
{file = "pypdfium2-4.30.1.tar.gz", hash = "sha256:5f5c7c6d03598e107d974f66b220a49436aceb191da34cda5f692be098a814ce"},
]
-[[package]]
-name = "pyproject-hooks"
-version = "1.2.0"
-requires_python = ">=3.7"
-summary = "Wrappers to call pyproject.toml-based build backend hooks."
-groups = ["dev"]
-files = [
- {file = "pyproject_hooks-1.2.0-py3-none-any.whl", hash = "sha256:9e5c6bfa8dcc30091c74b0cf803c81fdd29d94f01992a7707bc97babb1141913"},
- {file = "pyproject_hooks-1.2.0.tar.gz", hash = "sha256:1e859bd5c40fae9448642dd871adf459e5e2084186e8d2c2a79a824c970da1f8"},
-]
-
-[[package]]
-name = "pyproject-metadata"
-version = "0.9.1"
-requires_python = ">=3.7"
-summary = "PEP 621 metadata parsing"
-groups = ["dev"]
-dependencies = [
- "packaging>=19.0",
- "typing-extensions; python_version < \"3.8\"",
-]
-files = [
- {file = "pyproject_metadata-0.9.1-py3-none-any.whl", hash = "sha256:ee5efde548c3ed9b75a354fc319d5afd25e9585fa918a34f62f904cc731973ad"},
- {file = "pyproject_metadata-0.9.1.tar.gz", hash = "sha256:b8b2253dd1b7062b78cf949a115f02ba7fa4114aabe63fa10528e9e1a954a816"},
-]
-
[[package]]
name = "python-dateutil"
version = "2.9.0.post0"
@@ -3800,7 +3558,7 @@ name = "python-dotenv"
version = "1.1.0"
requires_python = ">=3.9"
summary = "Read key-value pairs from a .env file and set them as environment variables"
-groups = ["default", "dev"]
+groups = ["default"]
files = [
{file = "python_dotenv-1.1.0-py3-none-any.whl", hash = "sha256:d7c01d9e2293916c18baf562d95698754b0dbbb5e74d457c45d4f6561fb9d55d"},
{file = "python_dotenv-1.1.0.tar.gz", hash = "sha256:41f90bc6f5f177fb41f53e87666db362025010eb28f60a01c9143bfa33a2b2d5"},
@@ -4245,17 +4003,6 @@ files = [
{file = "requests_toolbelt-1.0.0-py2.py3-none-any.whl", hash = "sha256:cccfdd665f0a24fcf4726e690f65639d272bb0637b9b92dfd91a5568ccf6bd06"},
]
-[[package]]
-name = "resolvelib"
-version = "1.1.0"
-requires_python = ">=3.7"
-summary = "Resolve abstract dependencies into concrete ones"
-groups = ["dev"]
-files = [
- {file = "resolvelib-1.1.0-py2.py3-none-any.whl", hash = "sha256:f80de38ae744bcf4e918e27a681a5c6cb63a08d9a926c0989c0730bcdd089049"},
- {file = "resolvelib-1.1.0.tar.gz", hash = "sha256:b68591ef748f58c1e2a2ac28d0961b3586ae8b25f60b0ba9a5e4f3d87c1d6a79"},
-]
-
[[package]]
name = "rfc3339-validator"
version = "0.1.4"
@@ -4281,22 +4028,6 @@ files = [
{file = "rfc3986_validator-0.1.1.tar.gz", hash = "sha256:3d44bde7921b3b9ec3ae4e3adca370438eccebc676456449b145d533b240d055"},
]
-[[package]]
-name = "rich"
-version = "14.0.0"
-requires_python = ">=3.8.0"
-summary = "Render rich text, tables, progress bars, syntax highlighting, markdown and more to the terminal"
-groups = ["dev"]
-dependencies = [
- "markdown-it-py>=2.2.0",
- "pygments<3.0.0,>=2.13.0",
- "typing-extensions<5.0,>=4.0.0; python_version < \"3.11\"",
-]
-files = [
- {file = "rich-14.0.0-py3-none-any.whl", hash = "sha256:1c9491e1951aac09caffd42f448ee3d04e58923ffe14993f6e83068dc395d7e0"},
- {file = "rich-14.0.0.tar.gz", hash = "sha256:82f1bc23a6a21ebca4ae0c45af9bdbc492ed20231dcb63f297d6d1021a9d5725"},
-]
-
[[package]]
name = "rpds-py"
version = "0.24.0"
@@ -4569,17 +4300,6 @@ files = [
{file = "sgmllib3k-1.0.0.tar.gz", hash = "sha256:7868fb1c8bfa764c1ac563d3cf369c381d1325d36124933a726f29fcdaa812e9"},
]
-[[package]]
-name = "shellingham"
-version = "1.5.4"
-requires_python = ">=3.7"
-summary = "Tool to Detect Surrounding Shell"
-groups = ["dev"]
-files = [
- {file = "shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686"},
- {file = "shellingham-1.5.4.tar.gz", hash = "sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de"},
-]
-
[[package]]
name = "simple-websocket"
version = "1.1.0"
@@ -4616,17 +4336,6 @@ files = [
{file = "sniffio-1.3.1.tar.gz", hash = "sha256:f4324edc670a0f49750a81b895f35c3adb843cca46f0530f79fc1babb23789dc"},
]
-[[package]]
-name = "socksio"
-version = "1.0.0"
-requires_python = ">=3.6"
-summary = "Sans-I/O implementation of SOCKS4, SOCKS4A, and SOCKS5."
-groups = ["dev"]
-files = [
- {file = "socksio-1.0.0-py3-none-any.whl", hash = "sha256:95dc1f15f9b34e8d7b16f06d74b8ccf48f609af32ab33c608d08761c5dcbb1f3"},
- {file = "socksio-1.0.0.tar.gz", hash = "sha256:f88beb3da5b5c38b9890469de67d0cb0f9d494b78b106ca1845f96c10b91c4ac"},
-]
-
[[package]]
name = "soupsieve"
version = "2.6"
@@ -4886,17 +4595,6 @@ files = [
{file = "tomli-2.2.1.tar.gz", hash = "sha256:cd45e1dc79c835ce60f7404ec8119f2eb06d38b1deba146f07ced3bbc44505ff"},
]
-[[package]]
-name = "tomlkit"
-version = "0.13.2"
-requires_python = ">=3.8"
-summary = "Style preserving TOML library"
-groups = ["dev"]
-files = [
- {file = "tomlkit-0.13.2-py3-none-any.whl", hash = "sha256:7a974427f6e119197f670fbbbeae7bef749a6c14e793db934baefc1b5f03efde"},
- {file = "tomlkit-0.13.2.tar.gz", hash = "sha256:fff5fe59a87295b278abd31bec92c15d9bc4a06885ab12bcea52c71119392e79"},
-]
-
[[package]]
name = "torch"
version = "2.6.0"
@@ -5026,18 +4724,6 @@ files = [
{file = "triton-3.2.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e5dfa23ba84541d7c0a531dfce76d8bcd19159d50a4a8b14ad01e91734a5c1b0"},
]
-[[package]]
-name = "truststore"
-version = "0.10.1"
-requires_python = ">=3.10"
-summary = "Verify certificates using native system trust stores"
-groups = ["dev"]
-marker = "python_version >= \"3.10\""
-files = [
- {file = "truststore-0.10.1-py3-none-any.whl", hash = "sha256:b64e6025a409a43ebdd2807b0c41c8bff49ea7ae6550b5087ac6df6619352d4c"},
- {file = "truststore-0.10.1.tar.gz", hash = "sha256:eda021616b59021812e800fa0a071e51b266721bef3ce092db8a699e21c63539"},
-]
-
[[package]]
name = "types-python-dateutil"
version = "2.9.0.20241206"
@@ -5089,21 +4775,6 @@ files = [
{file = "typing_inspection-0.4.0.tar.gz", hash = "sha256:9765c87de36671694a67904bf2c96e395be9c6439bb6c87b5142569dcdd65122"},
]
-[[package]]
-name = "unearth"
-version = "0.17.5"
-requires_python = ">=3.8"
-summary = "A utility to fetch and download python packages"
-groups = ["dev"]
-dependencies = [
- "httpx<1,>=0.27.0",
- "packaging>=20",
-]
-files = [
- {file = "unearth-0.17.5-py3-none-any.whl", hash = "sha256:9963e66b14f0484644c9b45b517e530befb2de6a8da4b06a9a38bed2d086dfe6"},
- {file = "unearth-0.17.5.tar.gz", hash = "sha256:a19e1c02e64b40518d088079c7416fc41b45a648b81a4128aac02597234ee6ba"},
-]
-
[[package]]
name = "unstructured"
version = "0.17.2"
diff --git a/pyproject.toml b/pyproject.toml
index 885cbcc6f6..df9f34e3c1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -55,6 +55,7 @@ dependencies = [
"importlib-resources>=6.5.2",
"setuptools>=78.1.0",
"flask-wtf>=1.2.2",
+ "elasticsearch==8.14.0",
]
[project.urls]
diff --git a/src/local_deep_research/utilities/es_utils.py b/src/local_deep_research/utilities/es_utils.py
new file mode 100644
index 0000000000..34bc884569
--- /dev/null
+++ b/src/local_deep_research/utilities/es_utils.py
@@ -0,0 +1,441 @@
+"""
+Elasticsearch utilities for indexing and managing documents.
+"""
+
+import json
+import logging
+import os
+from typing import Any, Dict, List, Optional, Union
+
+from elasticsearch import Elasticsearch
+from elasticsearch.helpers import bulk
+
+logger = logging.getLogger(__name__)
+
+
+class ElasticsearchManager:
+ """
+ Utility class for managing Elasticsearch indices and documents.
+
+ This class provides methods for creating indices, indexing documents,
+ and performing other Elasticsearch management tasks.
+ """
+
+ def __init__(
+ self,
+ hosts: List[str] = ["http://localhost:9200"],
+ username: Optional[str] = None,
+ password: Optional[str] = None,
+ api_key: Optional[str] = None,
+ cloud_id: Optional[str] = None,
+ ):
+ """
+ Initialize the Elasticsearch manager.
+
+ Args:
+ hosts: List of Elasticsearch hosts
+ username: Optional username for authentication
+ password: Optional password for authentication
+ api_key: Optional API key for authentication
+ cloud_id: Optional Elastic Cloud ID
+ """
+ # Initialize the Elasticsearch client
+ es_args = {}
+
+ # Basic authentication
+ if username and password:
+ es_args["basic_auth"] = (username, password)
+
+ # API key authentication
+ if api_key:
+ es_args["api_key"] = api_key
+
+ # Cloud ID for Elastic Cloud
+ if cloud_id:
+ es_args["cloud_id"] = cloud_id
+
+ # Connect to Elasticsearch
+ self.client = Elasticsearch(hosts, **es_args)
+
+ # Verify connection
+ try:
+ info = self.client.info()
+ logger.info(f"Connected to Elasticsearch cluster: {info.get('cluster_name')}")
+ logger.info(f"Elasticsearch version: {info.get('version', {}).get('number')}")
+ except Exception as e:
+ logger.error(f"Failed to connect to Elasticsearch: {str(e)}")
+ raise ConnectionError(f"Could not connect to Elasticsearch: {str(e)}")
+
+ def create_index(
+ self,
+ index_name: str,
+ mappings: Optional[Dict[str, Any]] = None,
+ settings: Optional[Dict[str, Any]] = None,
+ ) -> bool:
+ """
+ Create an Elasticsearch index with optional mappings and settings.
+
+ Args:
+ index_name: Name of the index to create
+ mappings: Optional mappings for the index fields
+ settings: Optional settings for the index
+
+ Returns:
+ bool: True if successful, False otherwise
+ """
+ try:
+ # Check if index already exists
+ if self.client.indices.exists(index=index_name):
+ logger.warning(f"Index '{index_name}' already exists - skipping creation")
+ return True
+
+ # Default mappings for better text search if none provided
+ if mappings is None:
+ mappings = {
+ "properties": {
+ "title": {
+ "type": "text",
+ "analyzer": "standard",
+ "fields": {
+ "keyword": {
+ "type": "keyword",
+ "ignore_above": 256
+ }
+ }
+ },
+ "content": {
+ "type": "text",
+ "analyzer": "standard"
+ },
+ "url": {
+ "type": "keyword"
+ },
+ "source": {
+ "type": "keyword"
+ },
+ "timestamp": {
+ "type": "date"
+ },
+ "metadata": {
+ "type": "object",
+ "enabled": True
+ }
+ }
+ }
+
+ # Default settings if none provided
+ if settings is None:
+ settings = {
+ "number_of_shards": 1,
+ "number_of_replicas": 0,
+ "analysis": {
+ "analyzer": {
+ "standard": {
+ "type": "standard"
+ }
+ }
+ }
+ }
+
+ # Create the index with mappings and settings
+ create_response = self.client.indices.create(
+ index=index_name,
+ mappings=mappings,
+ settings=settings,
+ )
+
+ logger.info(f"Created index '{index_name}': {create_response}")
+ return True
+
+ except Exception as e:
+ logger.error(f"Error creating index '{index_name}': {str(e)}")
+ return False
+
+ def delete_index(self, index_name: str) -> bool:
+ """
+ Delete an Elasticsearch index.
+
+ Args:
+ index_name: Name of the index to delete
+
+ Returns:
+ bool: True if successful, False otherwise
+ """
+ try:
+ # Check if index exists
+ if not self.client.indices.exists(index=index_name):
+ logger.warning(f"Index '{index_name}' does not exist - skipping deletion")
+ return True
+
+ # Delete the index
+ delete_response = self.client.indices.delete(index=index_name)
+ logger.info(f"Deleted index '{index_name}': {delete_response}")
+ return True
+
+ except Exception as e:
+ logger.error(f"Error deleting index '{index_name}': {str(e)}")
+ return False
+
+ def index_document(
+ self,
+ index_name: str,
+ document: Dict[str, Any],
+ document_id: Optional[str] = None,
+ refresh: bool = False,
+ ) -> Optional[str]:
+ """
+ Index a single document in Elasticsearch.
+
+ Args:
+ index_name: Name of the index to add the document to
+ document: The document to index
+ document_id: Optional document ID (will be generated if not provided)
+ refresh: Whether to refresh the index after indexing
+
+ Returns:
+ str: Document ID if successful, None otherwise
+ """
+ try:
+ # Index the document
+ response = self.client.index(
+ index=index_name,
+ document=document,
+ id=document_id,
+ refresh=refresh,
+ )
+
+ logger.info(f"Indexed document in '{index_name}' with ID: {response['_id']}")
+ return response["_id"]
+
+ except Exception as e:
+ logger.error(f"Error indexing document in '{index_name}': {str(e)}")
+ return None
+
+ def bulk_index_documents(
+ self,
+ index_name: str,
+ documents: List[Dict[str, Any]],
+ id_field: Optional[str] = None,
+ refresh: bool = False,
+ ) -> int:
+ """
+ Bulk index multiple documents in Elasticsearch.
+
+ Args:
+ index_name: Name of the index to add the documents to
+ documents: List of documents to index
+ id_field: Optional field in the documents to use as the document ID
+ refresh: Whether to refresh the index after indexing
+
+ Returns:
+ int: Number of successfully indexed documents
+ """
+ try:
+ # Prepare the bulk actions
+ actions = []
+ for doc in documents:
+ action = {
+ "_index": index_name,
+ "_source": doc,
+ }
+
+ # Use the specified field as the document ID if provided
+ if id_field and id_field in doc:
+ action["_id"] = doc[id_field]
+
+ actions.append(action)
+
+ # Execute the bulk indexing
+ success, failed = bulk(
+ self.client,
+ actions,
+ refresh=refresh,
+ stats_only=True,
+ )
+
+ logger.info(f"Bulk indexed {success} documents in '{index_name}', failed: {failed}")
+ return success
+
+ except Exception as e:
+ logger.error(f"Error bulk indexing documents in '{index_name}': {str(e)}")
+ return 0
+
+ def index_file(
+ self,
+ index_name: str,
+ file_path: str,
+ content_field: str = "content",
+ title_field: Optional[str] = "title",
+ extract_metadata: bool = True,
+ refresh: bool = False,
+ ) -> Optional[str]:
+ """
+ Index a file in Elasticsearch, extracting text content and metadata.
+
+ Args:
+ index_name: Name of the index to add the document to
+ file_path: Path to the file to index
+ content_field: Field name to store the file content
+ title_field: Field name to store the file title (filename if not specified)
+ extract_metadata: Whether to extract file metadata
+ refresh: Whether to refresh the index after indexing
+
+ Returns:
+ str: Document ID if successful, None otherwise
+ """
+ try:
+ from langchain_community.document_loaders import UnstructuredFileLoader
+
+ # Extract file content and metadata
+ loader = UnstructuredFileLoader(file_path)
+ documents = loader.load()
+
+ # Combine all content from the documents
+ content = "\n\n".join([doc.page_content for doc in documents])
+
+ # Get the filename for the title
+ filename = os.path.basename(file_path)
+ title = filename
+
+ # Prepare the document
+ document = {
+ content_field: content,
+ }
+
+ # Add title if requested
+ if title_field:
+ document[title_field] = title
+
+ # Add metadata if requested
+ if extract_metadata and documents:
+ # Include metadata from the first document
+ document["metadata"] = documents[0].metadata
+
+ # Add file-specific metadata
+ document["source"] = file_path
+ document["file_extension"] = os.path.splitext(filename)[1].lstrip(".")
+ document["filename"] = filename
+
+ # Index the document
+ return self.index_document(index_name, document, refresh=refresh)
+
+ except ImportError:
+ logger.error("UnstructuredFileLoader not available. Please install the 'unstructured' package.")
+ return None
+ except Exception as e:
+ logger.error(f"Error indexing file '{file_path}': {str(e)}")
+ return None
+
+ def index_directory(
+ self,
+ index_name: str,
+ directory_path: str,
+ file_patterns: List[str] = ["*.txt", "*.pdf", "*.docx", "*.md"],
+ content_field: str = "content",
+ title_field: str = "title",
+ extract_metadata: bool = True,
+ refresh: bool = False,
+ ) -> int:
+ """
+ Index all matching files in a directory in Elasticsearch.
+
+ Args:
+ index_name: Name of the index to add the documents to
+ directory_path: Path to the directory containing files to index
+ file_patterns: List of file patterns to match (glob patterns)
+ content_field: Field name to store the file content
+ title_field: Field name to store the file title
+ extract_metadata: Whether to extract file metadata
+ refresh: Whether to refresh the index after indexing
+
+ Returns:
+ int: Number of successfully indexed files
+ """
+ try:
+ import glob
+
+ # Find all matching files
+ all_files = []
+ for pattern in file_patterns:
+ pattern_path = os.path.join(directory_path, pattern)
+ matching_files = glob.glob(pattern_path)
+ all_files.extend(matching_files)
+
+ logger.info(f"Found {len(all_files)} files matching patterns {file_patterns} in {directory_path}")
+
+ # Index each file
+ successful_count = 0
+ for file_path in all_files:
+ logger.info(f"Indexing file: {file_path}")
+ doc_id = self.index_file(
+ index_name=index_name,
+ file_path=file_path,
+ content_field=content_field,
+ title_field=title_field,
+ extract_metadata=extract_metadata,
+ refresh=refresh,
+ )
+
+ if doc_id:
+ successful_count += 1
+
+ logger.info(f"Successfully indexed {successful_count} files out of {len(all_files)}")
+ return successful_count
+
+ except Exception as e:
+ logger.error(f"Error indexing directory '{directory_path}': {str(e)}")
+ return 0
+
+ def search(
+ self,
+ index_name: str,
+ query: str,
+ fields: List[str] = ["content", "title"],
+ size: int = 10,
+ highlight: bool = True,
+ ) -> Dict[str, Any]:
+ """
+ Search for documents in Elasticsearch.
+
+ Args:
+ index_name: Name of the index to search
+ query: Search query
+ fields: Fields to search in
+ size: Maximum number of results to return
+ highlight: Whether to include highlighted excerpts in results
+
+ Returns:
+ Dict: Elasticsearch search response
+ """
+ try:
+ search_query = {
+ "query": {
+ "multi_match": {
+ "query": query,
+ "fields": fields,
+ "type": "best_fields",
+ "tie_breaker": 0.3,
+ }
+ },
+ "size": size,
+ }
+
+ # Add highlighting if requested
+ if highlight:
+ search_query["highlight"] = {
+ "fields": {field: {} for field in fields},
+ "pre_tags": ["<em>"],
+ "post_tags": ["</em>"],
+ }
+
+ # Execute the search
+ response = self.client.search(
+ index=index_name,
+ body=search_query,
+ )
+
+ return response
+
+ except Exception as e:
+ logger.error(f"Error searching index '{index_name}': {str(e)}")
+ return {"error": str(e)}
\ No newline at end of file
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index ad1da460d2..663ce96148 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -4,6 +4,7 @@ import os
import threading
import traceback
from datetime import datetime
+import hashlib
from ...config.llm_config import get_llm
from ...config.search_config import get_search
@@ -527,10 +528,13 @@ def run_research_process(
x for x in query if x.isalnum() or x in [" ", "-", "_"]
)[:50]
safe_query = safe_query.replace(" ", "_").lower()
+
+ # 生成一个不含中文字符的唯一文件名
+ query_hash = hashlib.md5(query.encode('utf-8')).hexdigest()[:10]
+
report_path = os.path.join(
OUTPUT_DIR,
- f"quick_summary_{safe_query}_"
- f"{datetime.now().isoformat()}.md",
+ f"quick_summary_{query_hash}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md",
)
# Send progress update for writing to file
@@ -641,9 +645,13 @@ def run_research_process(
x for x in query if x.isalnum() or x in [" ", "-", "_"]
)[:50]
safe_query = safe_query.replace(" ", "_").lower()
+
+ # 生成一个不含中文字符的唯一文件名
+ query_hash = hashlib.md5(query.encode('utf-8')).hexdigest()[:10]
+
report_path = os.path.join(
OUTPUT_DIR,
- f"detailed_report_{safe_query}_{datetime.now().isoformat()}.md",
+ f"detailed_report_{query_hash}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md",
)
with open(report_path, "w", encoding="utf-8") as f:
diff --git a/src/local_deep_research/web_search_engines/default_search_engines.py b/src/local_deep_research/web_search_engines/default_search_engines.py
new file mode 100644
index 0000000000..1d8339df78
--- /dev/null
+++ b/src/local_deep_research/web_search_engines/default_search_engines.py
@@ -0,0 +1,38 @@
+"""
+Default search engine configurations.
+This file can be used to initialize the search engine configurations.
+"""
+
+def get_default_elasticsearch_config():
+ """
+ Returns the default Elasticsearch search engine configuration.
+
+ Returns:
+ dict: Default configuration for Elasticsearch search engine
+ """
+ return {
+ "module_path": "local_deep_research.web_search_engines.engines.search_engine_elasticsearch",
+ "class_name": "ElasticsearchSearchEngine",
+ "requires_llm": True,
+ "default_params": {
+ "hosts": ["http://172.16.4.131:9200"],
+ "index_name": "sample_documents",
+ "highlight_fields": ["content", "title"],
+ "search_fields": ["content", "title"],
+ },
+ "description": "Search engine for Elasticsearch databases",
+ "strengths": "Efficient for searching document collections and structured data",
+ "weaknesses": "Requires an Elasticsearch instance and properly indexed data",
+ "reliability": "High, depending on your Elasticsearch setup",
+ }
+
+def get_default_search_engine_configs():
+ """
+ Returns a dictionary of default search engine configurations.
+
+ Returns:
+ dict: Dictionary of default search engine configurations
+ """
+ return {
+ "elasticsearch": get_default_elasticsearch_config(),
+ }
\ No newline at end of file
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
new file mode 100644
index 0000000000..5c4b5e1d46
--- /dev/null
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
@@ -0,0 +1,343 @@
+import json
+import logging
+from typing import Any, Dict, List, Optional
+
+from elasticsearch import Elasticsearch
+from langchain_core.language_models import BaseLLM
+
+from ...config import search_config
+from ..search_engine_base import BaseSearchEngine
+
+logger = logging.getLogger(__name__)
+
+
+class ElasticsearchSearchEngine(BaseSearchEngine):
+ """Elasticsearch search engine implementation with two-phase approach"""
+
+ def __init__(
+ self,
+ hosts: List[str] = ["http://localhost:9200"],
+ index_name: str = "documents",
+ username: Optional[str] = None,
+ password: Optional[str] = None,
+ api_key: Optional[str] = None,
+ cloud_id: Optional[str] = None,
+ max_results: int = 10,
+ highlight_fields: List[str] = ["content", "title"],
+ search_fields: List[str] = ["content", "title"],
+ filter_query: Optional[Dict[str, Any]] = None,
+ llm: Optional[BaseLLM] = None,
+ max_filtered_results: Optional[int] = None,
+ ):
+ """
+ Initialize the Elasticsearch search engine.
+
+ Args:
+ hosts: List of Elasticsearch hosts
+ index_name: Name of the index to search
+ username: Optional username for authentication
+ password: Optional password for authentication
+ api_key: Optional API key for authentication
+ cloud_id: Optional Elastic Cloud ID
+ max_results: Maximum number of search results
+ highlight_fields: Fields to highlight in search results
+ search_fields: Fields to search in
+ filter_query: Optional filter query in Elasticsearch DSL format
+ llm: Language model for relevance filtering
+ max_filtered_results: Maximum number of results to keep after filtering
+ """
+ # Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
+ super().__init__(
+ llm=llm, max_filtered_results=max_filtered_results, max_results=max_results
+ )
+
+ self.index_name = index_name
+ self.highlight_fields = highlight_fields
+ self.search_fields = search_fields
+ self.filter_query = filter_query or {}
+
+ # Initialize the Elasticsearch client
+ es_args = {}
+
+ # Basic authentication
+ if username and password:
+ es_args["basic_auth"] = (username, password)
+
+ # API key authentication
+ if api_key:
+ es_args["api_key"] = api_key
+
+ # Cloud ID for Elastic Cloud
+ if cloud_id:
+ es_args["cloud_id"] = cloud_id
+
+ # Connect to Elasticsearch
+ self.client = Elasticsearch(hosts, **es_args)
+
+ # Verify connection
+ try:
+ info = self.client.info()
+ logger.info(f"Connected to Elasticsearch cluster: {info.get('cluster_name')}")
+ logger.info(f"Elasticsearch version: {info.get('version', {}).get('number')}")
+ except Exception as e:
+ logger.error(f"Failed to connect to Elasticsearch: {str(e)}")
+ raise ConnectionError(f"Could not connect to Elasticsearch: {str(e)}")
+
+ def _get_previews(self, query: str) -> List[Dict[str, Any]]:
+ """
+ Get preview information for Elasticsearch documents.
+
+ Args:
+ query: The search query
+
+ Returns:
+ List of preview dictionaries
+ """
+ logger.info(f"Getting document previews from Elasticsearch with query: {query}")
+
+ try:
+ # Build the search query
+ search_query = {
+ "query": {
+ "multi_match": {
+ "query": query,
+ "fields": self.search_fields,
+ "type": "best_fields",
+ "tie_breaker": 0.3,
+ }
+ },
+ "highlight": {
+ "fields": {field: {} for field in self.highlight_fields},
+ "pre_tags": ["<em>"],
+ "post_tags": ["</em>"],
+ },
+ "size": self.max_results,
+ }
+
+ # Add filter if provided
+ if self.filter_query:
+ search_query["query"] = {
+ "bool": {
+ "must": search_query["query"],
+ "filter": self.filter_query
+ }
+ }
+
+ # Execute the search
+ response = self.client.search(
+ index=self.index_name,
+ body=search_query,
+ )
+
+ # Process the search results
+ hits = response.get("hits", {}).get("hits", [])
+
+ # Format results as previews with basic information
+ previews = []
+ for hit in hits:
+ source = hit.get("_source", {})
+ highlight = hit.get("highlight", {})
+
+ # Extract highlighted snippets or fall back to original content
+ snippet = ""
+ for field in self.highlight_fields:
+ if field in highlight and highlight[field]:
+ # Join all highlights for this field
+ field_snippets = " ... ".join(highlight[field])
+ snippet += field_snippets + " "
+
+ # If no highlights, use a portion of the content
+ if not snippet and "content" in source:
+ content = source.get("content", "")
+ snippet = content[:250] + "..." if len(content) > 250 else content
+
+ # Create preview object
+ preview = {
+ "id": hit.get("_id", ""),
+ "title": source.get("title", "Untitled Document"),
+ "link": source.get("url", "") or f"elasticsearch://{self.index_name}/{hit.get('_id', '')}",
+ "snippet": snippet.strip(),
+ "score": hit.get("_score", 0),
+ "_index": hit.get("_index", self.index_name),
+ }
+
+ previews.append(preview)
+
+ logger.info(f"Found {len(previews)} preview results from Elasticsearch")
+ return previews
+
+ except Exception as e:
+ logger.error(f"Error getting Elasticsearch previews: {str(e)}")
+ return []
+
+ def _get_full_content(
+ self, relevant_items: List[Dict[str, Any]]
+ ) -> List[Dict[str, Any]]:
+ """
+ Get full content for the relevant Elasticsearch documents.
+
+ Args:
+ relevant_items: List of relevant preview dictionaries
+
+ Returns:
+ List of result dictionaries with full content
+ """
+ # Check if we should get full content
+ if (
+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")
+ and search_config.SEARCH_SNIPPETS_ONLY
+ ):
+ logger.info("Snippet-only mode, skipping full content retrieval")
+ return relevant_items
+
+ logger.info("Getting full content for relevant Elasticsearch documents")
+
+ results = []
+ for item in relevant_items:
+ # Start with the preview data
+ result = item.copy()
+
+ # Get the document ID
+ doc_id = item.get("id")
+ if not doc_id:
+ # Skip items without ID
+ logger.warning(f"Skipping item without ID: {item}")
+ results.append(result)
+ continue
+
+ try:
+ # Fetch the full document
+ doc_response = self.client.get(
+ index=self.index_name,
+ id=doc_id,
+ )
+
+ # Get the source document
+ source = doc_response.get("_source", {})
+
+ # Add full content to the result
+ result["content"] = source.get("content", result.get("snippet", ""))
+ result["full_content"] = source.get("content", "")
+
+ # Add metadata from source
+ for key, value in source.items():
+ if key not in result and key not in ["content"]:
+ result[key] = value
+
+ except Exception as e:
+ logger.error(f"Error fetching full content for document {doc_id}: {str(e)}")
+ # Keep the preview data if we can't get the full content
+
+ results.append(result)
+
+ return results
+
+ def search_by_query_string(self, query_string: str) -> List[Dict[str, Any]]:
+ """
+ Perform a search using Elasticsearch Query String syntax.
+
+ Args:
+ query_string: The query in Elasticsearch Query String syntax
+
+ Returns:
+ List of search results
+ """
+ try:
+ # Build the search query
+ search_query = {
+ "query": {
+ "query_string": {
+ "query": query_string,
+ "fields": self.search_fields,
+ }
+ },
+ "highlight": {
+ "fields": {field: {} for field in self.highlight_fields},
+ "pre_tags": ["<em>"],
+ "post_tags": ["</em>"],
+ },
+ "size": self.max_results,
+ }
+
+ # Execute the search
+ response = self.client.search(
+ index=self.index_name,
+ body=search_query,
+ )
+
+ # Process and return the results
+ previews = self._process_es_response(response)
+ return self._get_full_content(previews)
+
+ except Exception as e:
+ logger.error(f"Error in query_string search: {str(e)}")
+ return []
+
+ def search_by_dsl(self, query_dsl: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """
+ Perform a search using Elasticsearch DSL (Query Domain Specific Language).
+
+ Args:
+ query_dsl: The query in Elasticsearch DSL format
+
+ Returns:
+ List of search results
+ """
+ try:
+ # Execute the search with the provided DSL
+ response = self.client.search(
+ index=self.index_name,
+ body=query_dsl,
+ )
+
+ # Process and return the results
+ previews = self._process_es_response(response)
+ return self._get_full_content(previews)
+
+ except Exception as e:
+ logger.error(f"Error in DSL search: {str(e)}")
+ return []
+
+ def _process_es_response(self, response: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """
+ Process Elasticsearch response into preview dictionaries.
+
+ Args:
+ response: Elasticsearch response dictionary
+
+ Returns:
+ List of preview dictionaries
+ """
+ hits = response.get("hits", {}).get("hits", [])
+
+ # Format results as previews
+ previews = []
+ for hit in hits:
+ source = hit.get("_source", {})
+ highlight = hit.get("highlight", {})
+
+ # Extract highlighted snippets or fall back to original content
+ snippet = ""
+ for field in self.highlight_fields:
+ if field in highlight and highlight[field]:
+ field_snippets = " ... ".join(highlight[field])
+ snippet += field_snippets + " "
+
+ # If no highlights, use a portion of the content
+ if not snippet and "content" in source:
+ content = source.get("content", "")
+ snippet = content[:250] + "..." if len(content) > 250 else content
+
+ # Create preview object
+ preview = {
+ "id": hit.get("_id", ""),
+ "title": source.get("title", "Untitled Document"),
+ "link": source.get("url", "") or f"elasticsearch://{self.index_name}/{hit.get('_id', '')}",
+ "snippet": snippet.strip(),
+ "score": hit.get("_score", 0),
+ "_index": hit.get("_index", self.index_name),
+ }
+
+ previews.append(preview)
+
+ return previews
\ No newline at end of file
diff --git a/src/local_deep_research/web_search_engines/search_engines_config.py b/src/local_deep_research/web_search_engines/search_engines_config.py
index 5d03c4fcd6..52a671c3d3 100644
--- a/src/local_deep_research/web_search_engines/search_engines_config.py
+++ b/src/local_deep_research/web_search_engines/search_engines_config.py
@@ -8,6 +8,7 @@ import logging
from typing import Any, Dict, List
from ..utilities.db_utils import get_db_setting
+from .default_search_engines import get_default_elasticsearch_config
logger = logging.getLogger(__name__)
@@ -61,6 +62,11 @@ def search_config() -> Dict[str, Any]:
# Add alias for 'auto' if it exists
if "auto" in search_engines and "meta" not in search_engines:
search_engines["meta"] = search_engines["auto"]
+
+ # Add Elasticsearch search engine if not already present
+ if "elasticsearch" not in search_engines:
+ logger.info("Adding default Elasticsearch search engine configuration")
+ search_engines["elasticsearch"] = get_default_elasticsearch_config()
# Register local document collections
local_collections_data = get_db_setting("search.engine.local", {})