ElasticSearch 是一个基于 Apache Lucene 的开源搜索引擎,它提供了分布式、实时的文档存储功能,并支持复杂的全文搜索。通过本文,我们将一步步学习如何快速搭建一个基于 ElasticSearch 的搜索应用。
ElasticSearch 是一种分布式搜索和分析引擎,适用于海量数据的存储、检索和分析。它使用 JSON 格式作为数据交互的标准,并支持 RESTful API 接口。其主要特点包括:
确保你的系统已安装以下组件:
可以通过以下命令检查 Java 版本:
java -version
你可以通过以下两种方式安装 ElasticSearch:
从官网下载最新版本的 ElasticSearch 压缩包:
wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-8.9.0-linux-x86_64.tar.gz
tar -xzf elasticsearch-8.9.0-linux-x86_64.tar.gz
cd elasticsearch-8.9.0/
运行 ElasticSearch:
./bin/elasticsearch
如果你已经安装了 Docker,可以使用以下命令快速启动 ElasticSearch:
docker run -d --name elasticsearch -p 9200:9200 -e "discovery.type=single-node" elasticsearch:8.9.0
访问地址:http://localhost:9200
在 ElasticSearch 中,索引类似于数据库中的表。我们可以使用 RESTful API 创建索引。
打开终端,执行以下命令创建一个名为 my_index
的索引:
curl -X PUT "http://localhost:9200/my_index" -H 'Content-Type: application/json' -d'
{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 0
}
}'
执行以下命令查看索引信息:
curl -X GET "http://localhost:9200/my_index"
接下来,我们向刚刚创建的索引中插入一些数据。
假设我们要存储一些书籍的信息:
{
"title": "Elasticsearch Basics",
"author": "John Doe",
"year": 2023
}
使用以下命令将数据插入到索引中:
curl -X POST "http://localhost:9200/my_index/_doc/1" -H 'Content-Type: application/json' -d'
{
"title": "Elasticsearch Basics",
"author": "John Doe",
"year": 2023
}'
重复上述步骤,插入更多数据以丰富索引。
ElasticSearch 提供强大的搜索功能。以下是一些常见的搜索操作示例。
搜索标题中包含“Elasticsearch”的书籍:
curl -X GET "http://localhost:9200/my_index/_search" -H 'Content-Type: application/json' -d'
{
"query": {
"match": {
"title": "Elasticsearch"
}
}
}'
结合多个条件进行搜索。例如,查找作者为“John Doe”且年份为2023的书籍:
curl -X GET "http://localhost:9200/my_index/_search" -H 'Content-Type: application/json' -d'
{
"query": {
"bool": {
"must": [
{ "match": { "author": "John Doe" } },
{ "match": { "year": "2023" } }
]
}
}
}'
ElasticSearch 默认使用标准分词器,但你可以根据需求配置自定义分词器。例如,添加中文分词器:
curl -X PUT "http://localhost:9200/my_index/_close"
curl -X PUT "http://localhost:9200/my_index" -H 'Content-Type: application/json' -d'
{
"settings": {
"analysis": {
"analyzer": {
"ik_smart": {
"type": "custom",
"tokenizer": "ik_smart"
}
}
}
}
}'
curl -X POST "http://localhost:9200/my_index/_open"
通过本文,我们学习了 ElasticSearch 的基本概念,并完成了以下任务:
ElasticSearch 的强大功能远不止于此,后续可以深入学习其高级特性,如聚合分析、跨集群搜索等。