ElasticSearch实战(八) QueryDSL

QueryDSL是Elasticsearch提供的JSON格式的领域特定语言,可以使用它来执行各种复杂查询。

HTTP请求示例:

GET /website/_search
{
	"query": {
		"match_all": {}
	}
}

 Spring-data-elasticsearch代码示例:

Request request = new Request("GET", "/website/_search");
request.setJsonEntity("{\"query\":{\"match_all\":{}}}");
Response response = restClient.performRequest(request);

查询全部并按日期倒序排列,取前10条

{
	"query": {
		"match_all": {}
	},
	"sort": {
		"date": {
			"order": "desc"
		}
	},
	"from": 0,
	"size": 10
}

查询author字段包含关键词Smith

{
	"query": {
		"match": {
			"author": "Smith"
		}
	}
}

查询点赞数等于40的文档

{
	"query": {
		"match": {
			"likes": "40"
		}
	}
}

查询text字段中包含短语"I like"并返回命中部分高亮信息

{
	"query": {
		"match_phrase": {
			"text": "I like"
		}
	},
	"highlight": {
		"fields": {
			"text": {}
		}
	}
}

在多个字段(author,text)中查询

{
	"query": {
		"multi_match": {
			"query": "I like Jane",
			"fields": ["author", "text"]
		}
	},
	"highlight": {
		"fields": {
			"text": {},
			"author": {}
		}
	}
}

bool查询使用布尔逻辑将基础的查询组成复杂的查询

查询author字段同时包含Smith和Jane

{
	"query": {
		"bool": {
			"must": [{
				"match": {
					"author": "Smith"
				}
			}, {
				"match": {
					"author": "Jane"
				}
			}]
		}
	}
}

查询author字段包含Smith或Jones,但不能包含Jane

{
	"query": {
		"bool": {
			"should": [{
				"match": {
					"author": "Smith"
				}
			}, {
				"match": {
					"author": "Jones"
				}
			}],
			"must_not": {
				"match": {
					"author": "Jane"
				}
			}
		}
	}
}

使用过滤器

{
	"query": {
		"bool": {
			"must": {
				"match_all": {}
			},
			"filter": [{
				"range": {
					"likes": {
						"gte": 20,
						"lte": 100
					}
				}
			}, {
				"term": {
					"author.keyword": "John Smith"
				}
			}]
		}
	}
}

聚合,统计每个作者发表的文档数量

{
	"size": 0,
	"aggs": {
		"group_by_author": {
			"terms": {
				"field": "author.keyword"
			}
		}
	}
}

聚合,统计每个作者发表的文档数量,且计算该作者发表的文档的点赞数平均值,并按该平均值倒序排列

{
	"size": 0,
	"aggs": {
		"group_by_author": {
			"terms": {
				"field": "author.keyword",
				"order": {
					"average_likes": "desc"
				}
			},
			"aggs": {
				"average_likes": {
					"avg": {
						"field": "likes"
					}
				}
			}
		}
	}
}

 

你可能感兴趣的:(ElasticSearch,Elasticsearch)