文集文档索引

Elasticsearch搜索引擎实战教程


  • 文集信息
  • 目录大纲
  • 最新文档
  • 知识宇宙

文集详情

文集导读

Elasticsearch Elasticsearch 代码实践与详解:从入门到进阶 一、Elasticsearch 核心概念 在深入代码之前,了解 Elasticsearch 的核心概念至关重要。 Index (索引): 类似于关系型数据库中的数据库,是文档的集合。 Document (文档): 类似于关系型数据库中的行,是可被索引的基本单元,通常以 JSON 格式表示。 Type (类型): (在 Elasticsearch 之前存在) 类似于关系型数据库中的表,用于对文档进行逻辑分组。在 Elasticsearch.x 中已移除,建议使用不同的索引来区分不同的数据类型。 Field (字段): 类似于关系型数据库中的列,是文档中的一个属性。 Mapping (映射): 定义了索引中文档的结构,包括字段的名称、数据类型和索引方式。 Node (节点): Elasticsearch 集群中的一个服务器实例。 Cluster (集群): 由一个或多个节点组成的整体,提供高可用性和可扩展性。 Shard (分片): 将索引分割成更小的部分,分布在不同的节点上,提高搜索性能和可扩展性。 Replica (副本): 索引分片的副本,提供数据冗余和高可用性。

Elasticsearch

Elasticsearch 代码实践与详解:从入门到进阶

一、Elasticsearch 核心概念

在深入代码之前,了解 Elasticsearch 的核心概念至关重要。

  • Index (索引): 类似于关系型数据库中的数据库,是文档的集合。

  • Document (文档): 类似于关系型数据库中的行,是可被索引的基本单元,通常以 JSON 格式表示。

  • Type (类型): (在 Elasticsearch 之前存在) 类似于关系型数据库中的表,用于对文档进行逻辑分组。在 Elasticsearch.x 中已移除,建议使用不同的索引来区分不同的数据类型。

  • Field (字段): 类似于关系型数据库中的列,是文档中的一个属性。

  • Mapping (映射): 定义了索引中文档的结构,包括字段的名称、数据类型和索引方式。

  • Node (节点): Elasticsearch 集群中的一个服务器实例。

  • Cluster (集群): 由一个或多个节点组成的整体,提供高可用性和可扩展性。

  • Shard (分片): 将索引分割成更小的部分,分布在不同的节点上,提高搜索性能和可扩展性。

  • Replica (副本): 索引分片的副本,提供数据冗余和高可用性。

二、环境搭建与客户端选择

  1. 安装 Elasticsearch: 可以从 Elasticsearch 官网下载对应平台的安装包,按照官方文档进行安装配置。

  2. 选择客户端: Elasticsearch 提供了多种客户端,方便不同语言的开发者进行交互。常用的客户端包括:

    • 官方客户端: 提供 Java、JavaScript、Go、.NET 等语言的官方客户端。

    • REST API: 通过 HTTP 请求直接与 Elasticsearch 的 REST API 进行交互。

    • 第三方客户端: 例如 Python 的 elasticsearch-py、PHP 的 elasticsearch/elasticsearch 等。

本文将以 Python 的 elasticsearch-py 为例进行代码演示。

pip install elasticsearch

三、基本操作:索引、文档、搜索

  1. 连接 Elasticsearch:
from elasticsearch import Elasticsearch # 连接到本地 Elasticsearch 实例 es = Elasticsearch([{'host': 'localhost', 'port': 9200}]) # 检查连接是否成功 if es.ping(): print("Connected to Elasticsearch") else: print("Could not connect to Elasticsearch!")
  1. 创建索引:
index_name = "my_index" # 定义索引的 mapping (可选) mapping = { "properties": { "title": {"type": "text"}, "content": {"type": "text"}, "author": {"type": "keyword"}, "date": {"type": "date", "format": "yyyy-MM-dd"} } } # 创建索引,如果存在则忽略 if not es.indices.exists(index=index_name): es.indices.create(index=index_name, body={"mappings": mapping}) print(f"Index '{index_name}' created successfully.") else: print(f"Index '{index_name}' already exists.")
  • es.indices.create() 方法用于创建索引。

  • body 参数用于指定索引的 settings 和 mappings。

  • mapping 定义了索引中文档的结构,包括字段的名称、数据类型和索引方式。

  1. 索引文档:
document = { "title": "Elasticsearch Tutorial", "content": "This is a tutorial about Elasticsearch.", "author": "John Doe", "date": "2023-10-27" } document_id = 1 # 索引文档 response = es.index(index=index_name, id=document_id, body=document) print(f"Document indexed with ID: {response['_id']}")
  • es.index() 方法用于索引文档。

  • index 参数指定索引名称。

  • id 参数指定文档 ID。如果未指定,Elasticsearch 会自动生成一个 ID。

  • body 参数指定文档内容。

  1. 获取文档:
response = es.get(index=index_name, id=document_id) print(f"Document retrieved: {response['_source']}")
  • es.get() 方法用于获取文档。
  1. 搜索文档:
query = { "match": { "content": "Elasticsearch tutorial" } } response = es.search(index=index_name, body={"query": query}) print(f"Search results:") for hit in response['hits']['hits']: print(f" - ID: {hit['_id']}, Score: {hit['_score']}, Source: {hit['_source']}")
  • es.search() 方法用于搜索文档。

  • body 参数指定查询语句。

  • match 查询用于全文搜索。

  1. 更新文档:
document_update = { "doc": { "content": "This is an updated tutorial about Elasticsearch." } } response = es.update(index=index_name, id=document_id, body=document_update) print(f"Document updated: {response}")
  • es.update() 方法用于更新文档。

  • doc 字段指定要更新的字段和值。

  1. 删除文档:
response = es.delete(index=index_name, id=document_id) print(f"Document deleted: {response}")
  • es.delete() 方法用于删除文档。
  1. 删除索引:
response = es.indices.delete(index=index_name) print(f"Index deleted: {response}")
  • es.indices.delete() 方法用于删除索引。

四、高级搜索技巧

  1. Bool Query: 组合多个查询条件。
query = { "bool": { "must": [ {"match": {"title": "Elasticsearch"}}, {"match": {"content": "tutorial"}} ], "must_not": [ {"match": {"author": "Jane Doe"}} ], "should": [ {"match": {"date": "2023-10-27"}} ] } }
  • must: 必须匹配的条件。

  • must_not: 必须不匹配的条件。

  • should: 应该匹配的条件,可以提高搜索结果的相关性。

  1. Range Query: 范围查询。
query = { "range": { "date": { "gte": "2023-10-20", "lte": "2023-10-30", "format": "yyyy-MM-dd" } } }
  • gte: 大于等于。

  • lte: 小于等于。

  • gt: 大于。

  • lt: 小于。

  1. Term Query: 精确匹配。
query = { "term": { "author": "John Doe" } }
  • 适用于 keyword 类型的字段。
  1. Aggregation: 聚合分析。
query = { "size": 0, "aggs": { "authors": { "terms": { "field": "author.keyword" } } } } response = es.search(index=index_name, body=query) print(f"Aggregation results:") for bucket in response['aggregations']['authors']['buckets']: print(f" - Author: {bucket['key']}, Count: {bucket['doc_count']}")
  • size: 0 表示只返回聚合结果,不返回文档。

  • terms 聚合用于统计每个 author 的文档数量。

五、Mapping 详解

Mapping 定义了索引中文档的结构,至关重要。常见的字段类型包括:

  • text: 用于全文搜索,会被分词器处理。

  • keyword: 用于精确匹配,不会被分词器处理。

  • date: 用于存储日期和时间。

  • integer: 用于存储整数。

  • float: 用于存储浮点数。

  • boolean: 用于存储布尔值。

  • geo_point: 用于存储地理坐标。

mapping = { "properties": { "title": {"type": "text", "analyzer": "standard"}, "content": {"type": "text", "analyzer": "ik_max_word"}, # 使用中文分词器 "author": {"type": "keyword"}, "date": {"type": "date", "format": "yyyy-MM-dd"}, "location": {"type": "geo_point"} } }
  • analyzer: 指定分词器,用于将文本分解成词条。常用的分词器包括 standard (默认), ik_max_word (中文分词器) 等。需要安装相应的分词器插件。

六、性能优化

  • 选择合适的分词器: 根据业务需求选择合适的分词器,可以提高搜索精度和性能。

  • 合理设置 Shard 和 Replica: Shard 数量影响搜索性能和可扩展性,Replica 数量影响数据冗余和高可用性。

  • 使用 Bulk API: 批量索引文档,减少网络开销。

from elasticsearch import helpers documents = [ {"_index": index_name, "_id": i, "_source": {"title": f"Document {i}", "content": f"Content of document {i}"}} for i in range(1000) ] helpers.bulk(es, documents)
  • 使用 Filter Context: 对于不需要计算相关性的查询,使用 Filter Context 可以提高性能。

七、总结

本文详细介绍了 Elasticsearch 的核心概念、基本操作和高级搜索技巧,并提供了相应的代码示例。 通过学习本文,你应该能够掌握 Elasticsearch 的基本使用方法,并能够根据实际业务需求进行灵活的应用。 Elasticsearch 的功能非常强大,希望你能继续深入学习,探索更多高级特性,例如:

  • Scripting: 使用脚本进行复杂的查询和计算。

  • Plugins: 安装插件扩展 Elasticsearch 的功能。

  • Monitoring: 监控 Elasticsearch 集群的健康状况。

祝你学习愉快!

目录大纲

    最新文档

    知识宇宙

    正在加载知识图谱...


    转发