Elasticsearch 的 search
查询 API 是其核心功能之一,用于在索引中搜索匹配特定条件的文档。以下是一系列关于 search
查询 API 的实战示例和操作说明:
一、基本搜索请求
1. 使用 HTTP API 进行基本搜索
curl -X GET "localhost:9200/my_index/_search" -H 'Content-Type: application/json' -d'
{
"query": {
"match_all": {}
}
}'
此请求将返回 my_index
索引中所有文档的简要信息(默认前10条)。
2. 使用 Kibana Dev Tools Console 进行基本搜索
GET my_index/_search
{
"query": {
"match_all": {}
}
}
二、查询条件
1. 全文搜索
使用 match
查询:
{
"query": {
"match": {
"title": "Elasticsearch"
}
}
}
2. 精确匹配
使用 term
查询:
{
"query": {
"term": {
"status": "published"
}
}
}
3. 范围查询
使用 range
查询:
{
"query": {
"range": {
"publish_date": {
"gte": "2024-01-01",
"lte": "2024-12-31"
}
}
}
}
4. 复合查询
使用 bool
查询进行逻辑组合:
{
"query": {
"bool": {
"must": [
{ "match": { "title": "Elasticsearch" } },
{ "range": { "publish_date": { "gte": "2024-01-01" } } }
],
"should": [
{ "term": { "category": "tutorials" } }
],
"filter": [
{ "term": { "status": "published" } }
],
"minimum_should_match": 1
}
}
}
三、分页与排序
1. 分页
使用 from
和 size
参数:
{
"from": 0,
"size": 10,
"query": {
"match_all": {}
}
}
2. 排序
使用 sort
参数:
{
"query": {
"match_all": {}
},
"sort": [
{ "publish_date": { "order": "desc" } },
{ "views": { "order": "asc", "unmapped_type": "long" } }
]
}
四、高亮显示
在搜索结果中突出显示匹配关键词:
{
"query": {
"match": {
"content": "Elasticsearch"
}
},
"highlight": {
"fields": {
"content": {}
}
}
}
五、聚合分析
使用 aggs
属性进行统计分析:
{
"query": {
"match_all": {}
},
"aggs": {
"by_category": {
"terms": {
"field": "category.keyword"
}
}
}
}
实战应用
- 使用
match
、term
、range
等查询条件构建搜索请求。 - 结合
from
、size
参数进行分页。 - 使用
sort
参数对结果进行排序。 - 添加
highlight
高亮匹配的关键词。 - 利用
aggs
属性进行聚合分析,提取统计数据。
通过熟练运用 search
查询 API,您可以构建各种复杂的搜索请求,满足多样化的查询需求。在实际操作中,请参阅Elasticsearch官方文档以获取最新的查询语法和最佳实践。