作为一款开源的分布式搜索和分析引擎,Elasticsearch在企业级搜索、日志分析等场景中应用广泛。初次接触ES的开发者往往会被其丰富的查询语法所困扰,今天我们就来拆解ES基础查询的核心要点。
提示:本文基于Elasticsearch 7.x版本,部分语法在早期版本可能不兼容
一个完整的ES查询请求包含以下几个核心部分:
json复制GET /index_name/_search
{
"query": {
"查询类型": {
"字段名": "查询条件"
}
},
"size": 10,
"from": 0,
"sort": [
{"字段名": {"order": "desc"}}
]
}
在实际使用中需要注意:
json复制// 过滤示例
{
"query": {
"bool": {
"filter": [
{"term": {"status": "published"}}
]
}
}
}
最常用的全文检索方式,会对查询文本进行分词处理:
json复制{
"query": {
"match": {
"content": "搜索引擎技术"
}
}
}
要求词语必须按顺序完整匹配:
json复制{
"query": {
"match_phrase": {
"content": {
"query": "搜索引擎技术",
"slop": 2 // 允许中间间隔的词数
}
}
}
}
精确匹配字段值,常用于keyword类型字段:
json复制{
"query": {
"term": {
"status": {
"value": "published"
}
}
}
}
匹配多个精确值:
json复制{
"query": {
"terms": {
"tags": ["技术","搜索"]
}
}
}
组合多个查询条件:
json复制{
"query": {
"bool": {
"must": [
{"match": {"title": "搜索引擎"}}
],
"should": [
{"match": {"content": "技术"}},
{"match": {"content": "原理"}}
],
"must_not": [
{"term": {"status": "draft"}}
],
"filter": [
{"range": {"publish_date": {"gte": "2023-01-01"}}}
]
}
}
}
可以调整特定条件的权重:
json复制{
"query": {
"boosting": {
"positive": {
"match": {
"content": "搜索引擎"
}
},
"negative": {
"match": {
"content": "广告"
}
},
"negative_boost": 0.5
}
}
}
ES默认限制最多返回10000条结果,深度分页推荐使用search_after:
json复制{
"size": 10,
"sort": [
{"_score": {"order": "desc"}},
{"publish_date": {"order": "desc"}}
],
"search_after": [0.5, "2023-05-20"]
}
可以基于脚本进行复杂排序:
json复制{
"sort": {
"_script": {
"type": "number",
"script": {
"source": "doc['view_count'].value * params.weight",
"params": {
"weight": 0.8
}
},
"order": "desc"
}
}
}
json复制{
"highlight": {
"fields": {
"content": {
"number_of_fragments": 3,
"fragment_size": 150
}
},
"pre_tags": ["<em>"],
"post_tags": ["</em>"]
}
}
json复制{
"mappings": {
"properties": {
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
}
}
}
}
bash复制GET /_analyze
{
"text": "搜索引擎技术",
"analyzer": "standard"
}
json复制{
"profile": true,
"query": {
"match": {"title": "搜索"}
}
}
yaml复制index.search.slowlog.threshold.query.warn: 10s
index.search.slowlog.threshold.query.info: 5s
在实际项目中使用ES查询时,我发现合理设计索引结构比优化查询语句更能显著提升性能。特别是在处理千万级数据时,提前规划好字段类型和分词策略可以避免后期大量的重构工作。对于复杂的业务场景,建议将bool查询的各个子句拆分测试,逐步组合出最优的查询方案。