PHP开发怎么使用 Elasticsearch 实现全文检索
更新时间:2023-10-05第一段:Elasticsearch 简介和基本概念
Elasticsearch 是一个分布式搜索引擎,它可以快速高效地检索海量数据,同时支持全文检索和结构化查询。它基于 Lucene,但是具有可扩展性和分布式性的优势。下面是一些 Elasticsearch 的基本概念:
// 创建一个 index
curl -X PUT "localhost:9200/books?pretty"
// 查询所有 index
curl -X GET "localhost:9200/_cat/indices?v"
// 创建一个 document
curl -X POST "localhost:9200/books/_doc?pretty" -H 'Content-Type: application/json' -d'
{
"title": "Elasticsearch: The Definitive Guide",
"author": "Clinton Gormley, Zachary Tong",
"publish_date": "2015-02-07",
"description": "A Distributed Real-Time Search and Analytics Engine",
"price": 21.52
}
'
// 搜索 documents
curl -X GET "localhost:9200/books/_search?q=author:Clinton&pretty"
第二段:使用 Elasticsearch 实现全文检索的核心思路
全文检索是一种基于文本的搜索方式,它可以在文档集合中匹配与搜索关键字相关的文档。Elasticsearch 能够快速实现全文检索,主要基于以下三个核心部分:索引、类型和文档。
// 创建一个 index
curl -X PUT "localhost:9200/products?pretty"
// 创建一个 type
curl -X PUT "localhost:9200/products/phone/1?pretty" -H 'Content-Type: application/json' -d'
{
"brand": "iPhone",
"model": "12 Pro Max",
"ram": "6 GB",
"price": 1099
}
'
// 创建多个 types,使用 _bulk API
curl -X POST "localhost:9200/products/_bulk?pretty" -H 'Content-Type: application/x-ndjson' -d'
{ "create" : { "_index" : "products", "_type" : "phone", "_id" : "2" } }
{ "brand": "Samsung", "model": "Galaxy S21 Ultra", "ram": "12 GB", "price": 1199 }
{ "create" : { "_index" : "products", "_type" : "laptop", "_id" : "3" } }
{ "brand": "Apple", "model": "MacBook Pro", "ram": "16 GB", "price": 1999 }
'
// 搜索
curl -X GET "localhost:9200/products/_search?q=brand:iPhone&pretty"
第三段:实现 Elasticsearch 全文检索的流程和步骤
要实现 Elasticsearch 的全文检索,需要以下三个步骤:定义 mapping、创建索引、搜索文档。
// 定义 mapping
curl -X PUT "localhost:9200/books?pretty" -H 'Content-Type: application/json' -d'
{
"mappings": {
"properties": {
"title": { "type": "text" },
"author": { "type": "text" },
"publish_date": { "type": "date" },
"description": { "type": "text" },
"price": { "type": "float" }
}
}
}
'
// 创建索引,并添加文档
curl -X PUT "localhost:9200/books/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
"title": "Elasticsearch: The Definitive Guide",
"author": "Clinton Gormley, Zachary Tong",
"publish_date": "2015-02-07",
"description": "A Distributed Real-Time Search and Analytics Engine",
"price": 21.52
}
'
// 再添加一个文档
curl -X PUT "localhost:9200/books/_doc/2?pretty" -H 'Content-Type: application/json' -d'
{
"title": "Mastering Elasticsearch",
"author": "Rafal Kuc",
"publish_date": "2016-03-10",
"description": "Build scalable search applications using Elasticsearch, Logstash, and Kibana",
"price": 27.99
}
'
// 全文检索
curl -X GET "localhost:9200/books/_search?q=elasticsearch&pretty"
第四段:总结
全文检索是一种广泛应用于各大搜索引擎和数据库中的搜索技术。Elasticsearch 是其中一种常用的全文检索引擎,它使用了分布式的集群机制,可以应对大规模的查询需求。要使用 Elasticsearch 进行全文检索,首先需要对文档进行索引和配置 mapping,然后根据搜索条件执行简单的查询操作就可以了。