es的高级查询分为两种:
- 子条件查询 特定字段查询所指特定值
- 复合条件查询 以一定的逻辑组合子条件查询
1. 子条件查询
子条件查询分为两种:
- Query Context
- Filter Context
1.1 Query Context
在查询过程中,除了判断文档是否满足查询条件外,ES还会计算一个_score来标识匹配的程度,旨在判断目标文档和查询条件匹配的有多好
-
全文本查询 针对文本类型数据
-
字段级别查询 针对结构化数据,如数字,日期等
以下为全文本查询
1.1.1 模糊匹配查询 match
127.0.0.1:9200/book/_search POST请求
{
"query" : {
"match" : {
"author" : "harvey"
}
}
}
1.1.2 短语匹配 match_phrase
短语匹配,即精确匹配,但并不能保证一定能匹配到正确的结果,因为分词的结果可能会有变动 s关于Elasticsearch 使用 MatchPhrase搜索的一些坑
127.0.0.1:9200/book/_search POST请求
{
"query" : {
"match_phrase" : {
"author" : "harvey"
}
}
}
1.1.3 多字段查询 multi_match
127.0.0.1:9200/book/_search POST请求
{
"query" : {
"multi_match" : {
"query" : "harvey",
"fields" : ["author","name"]
}
}
}
1.1.4 语法查询 query_string
(harvey AND tuan) 指的是将查询内容分词后,分为Harvey 和 tuan, OR 指的是或者满足之后的条件的内容查询
127.0.0.1:9200/book/_search POST请求
{
"query" : {
"query_string" : {
"query" : "(harvey AND tuan) OR design"
}
}
}
多字段模糊匹配
{
"query" : {
"query_string" : {
"query" : "(harvey AND tuan) OR design",
"fields" : ["author","title"]
}
}
}
以下为字段级别查询 字段级别查询,即结构化数据查询
使用term具体项来查询
127.0.0.1:9200/book/_search POST请求
{
"query" : {
"term" : {
"number" : 10
}
}
}
范围查询,gte >=, lte<=
{
"query" : {
"range" : {
"number" : {
"gte" : 3,
"lte" : 15
}
}
}
}
1.2 Filter Context
在查询过程中,只判断该文档是否满足条件,只有YES或NO,用来作数据过滤用。返回的数据中只有完全匹配的信息才会展示。而且ES会对filter的数据进行缓存。因此经常将两者结合起来一起使用。
127.0.0.1:9200/book/_search POST请求
{
"query" : {
"bool" : {
"filter" : {
"term" : {
"author" : "harvey"
}
}
}
}
}
1.3 复合条件查询
常用的查询有
-
固定分数查询
-
布尔查询
-
....
1.3.1 固定分数查询
将匹配查询到内容中的 _score 固定化,只支持filter查询。
127.0.0.1:9200/book/_search POST请求
{
"query" : {
"constant_score" : {
"filter" : {
"match" : {
"author" : "harvey"
}
},
"boost" : 2
}
}
}
如果加上boost参数,则可以指定固化的分数值,不指定默认为1
布尔查询,
should ---两者任意match即可,
must --- 两者都同时匹配才可以,
must_not --- 两者都不符合的才可以
{
"query" : {
"bool" : {
"should" : [
{
"match" : {
"author" : "harvey"
}
},
{
"match" : {
"name" : "设计"
}
}
]
}
}
}