Elasticsearch中对文章进行索引和查重

解决思路

要在Elasticsearch中对文章进行索引和查重,可以按照以下步骤操作:

  1. 安装Elasticsearch并启动服务。

  2. 安装Python的Elasticsearch客户端库,可以使用pip install elasticsearch命令进行安装。

  3. 编写Python代码,使用Elasticsearch客户端库对文章进行索引和查重。

示例代码

python 复制代码
from elasticsearch import Elasticsearch

# 连接到Elasticsearch服务
es = Elasticsearch(["http://localhost:9200"])

# 定义要索引的文章
articles = [
    {"title": "文章1", "content": "这是文章1的内容"},
    {"title": "文章2", "content": "这是文章2的内容"},
    {"title": "文章3", "content": "这是文章3的内容"},
]

# 对文章进行索引
for article in articles:
    es.index(index="articles", doc_type="_doc", body=article)

# 查询相似度较高的文章
query = {
    "query": {
        "more_like_this": {
            "fields": ["content"],
            "like": "这是文章1的内容",
            "min_term_freq": 1,
            "max_query_terms": 12,
        }
    }
}

# 执行查询
response = es.search(index="articles", body=query)

# 输出查询结果
print("相似度较高的文章:")
for hit in response["hits"]["hits"]:
    print(hit["_source"]["title"])
复制代码

这个示例代码首先连接到Elasticsearch服务,然后定义了三篇文章并对它们进行索引。接下来,我们使用more_like_this查询来查找与给定文章内容相似的文章。最后,输出查询结果。

more_like_this查询

在Elasticsearch中,more_like_this查询用于查找与给定文档相似的文档。它基于文档的文本内容,通过计算文档之间的相似度来返回最相似的文档。

以下是more_like_this查询的基本用法:

  1. 指定要查询的索引和文档类型。
  2. 使用query字段定义查询条件,其中包含more_like_this查询。
  3. more_like_this查询中,需要指定要比较的字段(通常是文本类型的字段),以及要与之比较的文档。
  4. 可以设置其他参数,如最小词频(min_term_freq)、最大查询词数(max_query_terms)等,以控制相似度计算的方式。
python 复制代码
{
  "query": {
    "more_like_this": {
      "fields": ["title", "content"],
      "like": "这是一个示例文档",
      "min_term_freq": 1,
      "max_query_terms": 12
    }
  }
}

在这个示例中,我们指定了要查询的索引和文档类型(省略了这些部分,因为它们是通用的)。然后,我们在more_like_this查询中指定了要比较的字段(titlecontent),以及要与之比较的文档(这是一个示例文档)。我们还设置了最小词频为1,最大查询词数为12。

执行这个查询后,Elasticsearch会返回与给定文档相似的文档列表。

相关推荐
SelectDB9 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
ApacheSeaTunnel12 小时前
当多表数据涌入,Apache SeaTunnel 如何巧妙化解主键冲突?
大数据·开源·数据集成·seatunnel·技术分享·数据同步
Elasticsearch17 小时前
使用 Elastic Agent Builder 和 Sarvam AI 构建多语言语音 agent
elasticsearch
大大大大晴天3 天前
Hudi Metadata Table 与 Hive Sync (HMS)怎么选?
大数据
手可摘星辰7774 天前
一次线上FlinkCDC异常排查复盘
大数据·flink
大大大大晴天4 天前
Hudi技术内幕:Metadata Table原理与实践
大数据
武子康5 天前
调查研究-197 FAISS vs Elasticsearch 全面对比:从向量检索、全文搜索到 RAG 选型指南
人工智能·elasticsearch·agent
大大大大晴天5 天前
Hudi技术内幕:深入解析Index索引机制
大数据
阿里云大数据AI技术5 天前
Flink Forward Asia 2026 深圳启幕:Agentic Streaming for AI,开启实时智能新范式
大数据·flink
SelectDB5 天前
阶跃星辰基于 SelectDB 构建 PB 级 Agent 可观测平台
大数据·数据库·aigc