ElasticSearch ( 四 ) 查询操作

4.4.查询

4.4.0.查询分类

4.4.0.1.url查询
GET /bank/_search?q=*&sort=account_number:asc

返回结果

{
  "took" : 29,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1000,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [
      {
        "_index" : "bank",
        "_type" : "account",
        "_id" : "0",
        "_score" : null,
        "_source" : {
          "account_number" : 0,
          "balance" : 16623,
          "firstname" : "Bradshaw",
          "lastname" : "Mckenzie",
          "age" : 29,
          "gender" : "F",
          "address" : "244 Columbus Place",
          "employer" : "Euron",
          "email" : "bradshawmckenzie@euron.com",
          "city" : "Hobucken",
          "state" : "CO"
        },
        "sort" : [
          0
        ]
      },
      {...},...  #只返回 10 条记录, 相当于分页
    ]
  }
}

4.4.0.2.QueryDSL 语言

这是一个基于 JSON 定义的查询语言,主要包含两种类型:

字段查询:如 term、match、range等,只针对某一字段进行查询

复合查询:如bool查询等,包含一个或多个字段类查询或复合查询语句

query 参数表示整个语句是处于 query context 中

bool 和 match 语句被用在 query context 中,也就是说它们会计算每个文档的匹配度(_score)

GET /bank/_search
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "account_number": "asc"
    }
  ]
}

返回的结果与 url 查询效果相同

4.4.0.3.与SQL对比

运行时 —xxx 要删除, 才能运行

GET /bank/_search   --- from
{
  "_source": {      --- select
    "includes": ["account_number","firstname","lastname", "balance", "gender","address"],
    "excludes": ["age","employer","email"]
  },
  "query": {    --- where
    "bool": {   --- and
       "must": [
        {
          "match": {
            "gender.keyword": "M"
          }
        },{
          "match":{
            "address": "mill Lane"
          }
        }
      ]
    }
  },
  "aggs": {  --- group by
    "ageAgg": {
      "terms": {
        "field": "age",
        "size": 10
      }
    },
    "balanceAvg":{
      "avg": {
        "field": "balance"
      }
    }
  },
  "from": 1,   --- limit
  "size": 4,
  "sort":{     --- order by
    "balance":"desc"
  }
}

4.4.1._source : — SELECT

以JSON数组格式,传入需要(不需要)的字段。

4.4.1.1.指定需要的字段
GET /bank/_search
{
   "_source": ["account_number","firstname","lastname", "balance", "gender","address"]
}
4.4.1.2.指定不需要的字段
GET /bank/_search
{
   "_source": {  
    "excludes": ["age","employer","email"]
  }
}
4.4.1.3.即指定需要的也指定不需要的
GET /bank/_search
{
   "_source": {  
   	"includes": ["account_number","firstname","lastname", "balance", "gender","address"],
    "excludes": ["age","employer","email"]
  }
}

4.4.2.query : — where

查询所有:查询出所有数据,一般测试用。例如:
● match_all
全文检索(full text)查询:利用分词器对用户输入内容分词,然后去倒排索引库中匹配。例如:
● match_query
● multi_match_query
精确查询:根据精确词条值查找数据,一般是查找keyword、数值、日期、boolean等类型字段。例如:
● ids
● range (根据数值范围做查询)
● term (按精确值查询)
地理(geo)查询:根据经纬度查询。例如:
● geo_distance
● geo_bounding_box
复合(compound)查询:复合查询可以将上述各种查询条件组合起来,合并查询条件。例如:
● bool (组合起来利用逻辑运算查询)
● function_score

4.4.3.match_all 全查

可以使用 match_all 来查询指定索引下的所有文档, 所有的 _score 都是 1.0。

使用 match_all,默认只会返回 10条数据。

原因:_search查询默认采用的是分页查询,每页记录数 size的默认值为 10。如果想显示更多数据,指定 size 。

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

4.4.4.match 模糊匹配

# match查询 模板
GET /索引名称/_search
{
  "query": {
    "match": {
      "属性名": "text值"       # 字段
    }
  }
}

字符串 查询是 分词查询, 结果按评分 _score 降序排序

_score 是通过 倒排索引 得到的

4.4.4.1.模糊匹配

可以使用 match 进行全文搜索匹配(类似于 SQL 中的 like %%),搜索的字段类型要是 text 类型才能生效。

字符串 查询是 分词查询, 结果按评分 _score 降序排序

_score 是通过 倒排索引 得到的

得到的结果包含mill , lane, mill lane 及大小写

# 模糊匹配
GET /bank/_search
{
  "query":{
    "match": {
       "address": "mill lane"
    }
  }
}

非字符串 查询 是精确查询

GET /bank/_search
{
  "query":{
    "match": {
      "account_number": "22"
    }
  }
}
4.4.4.2.细节
  • query:指定匹配的值
  • operator:匹配条件类型
    • and:条件分词后都要匹配
    • or:条件分词后有一个匹配即可(默认)
  • minmum_should_match :最低匹配度,即条件在倒排索引中最低的匹配度
#模糊匹配 match 分词后or的效果 
GET /bank/_search
{
  "query":{
    "match": {
       "address": "mill lane"
    }
  }
}

#分词后 and的效果 
GET /bank/_search
{
  "query": {
    "match": {
      "address": {
        "query": "mill lane",
        "operator": "and"
      }
    }
  }
}

当 operator参数设置为 or时,minnum_should_match参数用来控制匹配的分词的最少数量。

#最少匹配 mill ,  lane 两个词 
GET /bank/_search
{
  "query": {
    "match": {
      "address": {
        "query": "mill lane",
        "operator": "or",
        "minimum_should_match": 2
      }
    }
  }
}
4.4.4.3.match_phrase 包含匹配短语

完全匹配查询, 查询的结果是包含匹配短语的

GET /bank/_search
{
  "query":{
    "match_phrase": {
      "address": "mill lane"
    }
  }
}
4.4.4.4.multi_match 多字段全文检索

有的时候同一个搜索请求,要应用到多个字段上,那么使用 multi_match 即可实现

针对 多个字段进行分词查询

GET /bank/_search
{
  "query": {
    "multi_match": {
      "query": "mill bynum",
      "fields": ["address","city"]
    }
  }
}
4.4.4.5.wildcard 通配符检索

使用wildcard相当于SQL的like,前后都可拼接*,匹配0到多个任意字符

# 通配匹配
GET /bank/_search
{
    "query": {
        "wildcard": {
            "address.keyword": "*m*"
        }
    }
}

4.4.5.精确匹配

4.4.5.1.数值精确

非字符串 查询 是精确查询

GET /bank/_search
{
  "query":{
    "match": {
      "age": 32
    }
  }
}
4.4.5.2.keyword 精确

如果要 完整匹配, .keyword , 只有 address 属性的值 是 “mill lane” 才能查询到

GET /bank/_search
{
  "query":{
    "match": {
      "address.keyword": "mill lane"
    }
  }
}
4.4.5.3.term 精确查询 (不分词)

根据精确值进行查询,类似于 SQL 中的 =

通常 非 字符串型 查询 使用

GET /bank/_search
{
  "query":{
    "term": {
      "account_number": "22"
    }
  }
}

GET /bank/_search
{
  "query":{
    "term": {
      "address": "mill lane"
    }
  }
}
4.4.5.4.terms 多值精确查询

terms 可以匹配多个值,类似于 SQL 中的 in(...)

GET /bank/_search
{
  "query": {
    "terms": {
      "age": [ 32, 33, 34]
    }
  }
}
4.4.5.5.ids 主键查询

根据多个主键查询,类似于 SQL 中的 id in (...)

GET /bank/_search
{
  "query": {
    "ids": {
      "values": [3, 4, 5]
    }
  }
}

4.4.6.range 范围

参数名描述
gt(可选)大于。
gte(可选)大于等于
lt(可选)小于
lte(可选)小于等于
format(可选,字符串)用于转换查询中日期值的日期格式。默认情况下,Elasticsearch 使用 映射中提供的日期格式。此值会覆盖该映射格式。
relation(可选,字符串)指示范围查询如何匹配范围字段的值。有效值为:INTERSECTS (默认), 匹配具有与查询范围相交的范围字段值的文档。 CONTAINS,匹配具有完全包含查询范围的范围字段值的文档。WITHIN,匹配具有完全在查询范围内的范围字段值的文档。
time_zone(可选,字符串)用于将查询中的日期值转换为 UTC 的偏移量或 IANA 时区。有效值为 ISO 8601 UTC 偏移量,例如 +01:00 或 -08:00,以及 IANA 时区 ID,例如 America/Los_Angeles。
boost(Optional, float) 用于降低或提高查询相关性得分的浮点数。默认为1.0。

range的限制

如果 search.allow_expensive_queries 设置为 false,则不会执行对文本或关键字字段的范围查询。

4.4.6.1.数值范围

数值型 >= (lte) 小于等于 <= (gte) 大于等于

GET /bank/_search
{
  "query":{
    "range": {
      "age": {
          "gte": 31,
          "lte": 42
        }
    }
  }
}


# 数值型    < (gt) 大于
GET /bank/_search
{
  "query":{
    "range": {
      "age": {
          "gt": 31
        }
    }
  }
}


# 数值型    >= (lte) 小于等于  
GET /bank/_search
{
  "query":{
    "range": {
      "age": {

          "lte": 42
        }
    }
  }
}

4.4.7.bool 逻辑查询(多个子查询)

逻辑查询就是一个或多个子句的组合,每一个子句都是一个子查询

对应关键字说明
must必须匹配每个子句,类似于 SQL 中的 and,参与评分。
should可以匹配任意子句,类似于 SQL 中的 or,参与评分。
must_not必须不匹配每个子类,类似于 SQL中的 not in,不参与评分。
filter过滤上下文,它与 must 的不同之处是不会影响匹配文档的分数。
4.4.7.1.must 必须匹配

必需满足 gender为 M, 并且 address 包含 mill

GET /bank/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "gender": "M"
          }
        },
        {
          "match": {
            "address": "mill"
          }
        }
      ]
    }
  }
}
4.4.7.2.should 可以匹配

查询 gender为 M, 或者 address 包含 mill
满足任意条件,用的ES语句是 "minimum_should_match": 1

GET /bank/_search
{
  "query": {
    "bool": {
      "minimum_should_match": 1,
      "should": [
        {
          "match": {
            "lastname": "Holland"
          }
        },
        {
          "match": {
            "gender": "M"
          }
        },
        {
          "match": {
            "address": "mill"
          }
        }
      ]
    }
  }
}
4.4.7.3.must_not 不匹配

查询 sex 不为 男 并且 age 不大于12

GET /bank/_search
{
  "query": {
    "bool": {
  	  "must_not": [
        {
          "match": {
            "age": "28"
          }
        }
      ]
    }
  }
}
4.4.7.4.filter 过滤器

filter 过滤的结果与must是一样的, 但 _score 都是 0.0。

先, 可以通过 查询条件来

GET /bank/_search
{
  "query": {
    "bool": {
      "must": [
        {"range": {
          "age": {
            "gte": 20,
            "lte": 30
          }
        }}
      ]
    }
  }
}

也, 可以通过 filter

GET /bank/_search
{
  "query": {
    "bool": {
      "filter": [
        {"range": {
           "age": {
            "gte": 20,
            "lte": 30
          }
        }}
      ]
    }
  }
}

得到 的查询结果是一样的

但 filter 得到的结果, 不计算分数

4.5.aggregations聚合分析

聚合函数 与 分组

4.5.0. aggregations聚合分析结构

GET /索引名称/_search
{
  "query":{
    ...
  },
  "aggs":{
    "指定聚合名字":{
      "指定聚合方式":{
        "field":"按那个字段聚合"
      }
    }
  }
}

4.5.1.统计

terms 统计 类似 count

avg 平均值
sum 合计值

  • Metrics Aggregations 指标聚合 :提供了类似于关系型数据库的 count,sum,avg,min,max 等统计方式。
## 搜索address中包含mill的所有人的年龄分布以及平均年龄
GET bank/_search
{
  "query":{
    "match": {
      "address": "mill"
    }
  },
  "aggs": {
    "ageAgg": {
      "terms": {
        "field": "age",
        "size": 10,
        "min_doc_count": 55
      }
    },
    "ageAvg":{
      "avg": {
        "field": "age"
      }
    },
    "balanceAvg":{
      "avg": {
        "field": "balance"
      }
    }
  },
  "size": 20
}

运行结果 :

"aggregations" : {
    "ageAgg" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : 38,
          "doc_count" : 2
        },
        {
          "key" : 28,
          "doc_count" : 1
        },
        {
          "key" : 32,
          "doc_count" : 1
        }
      ]
    },
    "ageAvg" : {
      "value" : 34.0
    },
    "balanceAvg" : {
      "value" : 25208.0
    }
  }

4.5.2.对聚合结果,进行聚合

  • Pipeline Aggregations 管道聚合 : 管道聚合主要是把其他聚合的结果再进行聚合
##按照年龄聚合,并且请求这些年龄段的这些人的平均薪资 

GET /bank/_search
{
  "query":{
    "match": {
      "address": "mill"
    }
  },
  "aggs": {
    "ageAgg": {
      "terms": {
        "field": "age",
        "size": 10
      },
      "aggs": {
        "balanceAvg": {
          "avg": {
            "field": "balance"
          }
        }
      }
    }
  }
}

运行结果 :

  "aggregations" : {
    "ageAgg" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : 38,
          "doc_count" : 2,
          "ageAgg" : {
            "value" : 27806.5
          }
        },
        {
          "key" : 28,
          "doc_count" : 1,
          "ageAgg" : {
            "value" : 19648.0
          }
        },
        {
          "key" : 32,
          "doc_count" : 1,
          "ageAgg" : {
            "value" : 25571.0
          }
        }
      ]
    }
  }

4.5.3.对聚合结果,分别再聚合

## 查出所有年龄分布,并且这些年龄段中性别是M的平均薪资和性别是F的平均薪资以及这个年龄的总体平均薪资

GET /bank/_search
{
  "query": {
    "match_all": {}
  },
  "aggs": {
    "ageAgg": {
      "terms": {
        "field": "age",
        "size": 100
      },
      "aggs": {
        "genderAgg": {
          "terms": {
            "field": "gender.keyword",
            "size": 10
          },
          "aggs": {
            "balanceAvg": {
              "avg": {
                "field": "balance"
              }
            }
          }
        }
      }
    }
  }
}

运行结果 :

"aggregations" : {
    "ageAgg" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : 31,
          "doc_count" : 61,
          "genderAgg" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : "M",
                "doc_count" : 35,
                "balanceAvg" : {
                  "value" : 29565.628571428573
                }
              },
              {
                "key" : "F",
                "doc_count" : 26,
                "balanceAvg" : {
                  "value" : 26626.576923076922
                }
              }
            ]
          }
        },
        {...},...
      ]
     }
    }

4.6.sort 排序

asc 升序 desc 降序

# 年龄 升序
GET /bank/_search
{
  "query": {
    "match_all": {}
  },
  "sort": {
    "age": "asc"
  }
}

# 年龄 降序
GET /bank/_search
{
  "query": {
    "match_all": {}
  },
  "sort": {
    "age": "desc"
  }
}


# 年龄降序 , 体重升序
GET /bank/_search
{
  "query": {
    "match_all": {}
  },
  "sort":[ {
      "age": "desc"
  },{
    "balance": "asc"
  }]
}

4.7.from / size 分页

类似 limit

“from” 从哪条开始
“size” 最多查多少条

4.7.1.size 查询条数

默认 10 条, 只查询 2 条

GET /bank/_search
{
  "query": {
    "match_all": {}
  },
  "size": 20
}

如果 size = 30000,,就会出现异常。

4.7.2.from 从哪条开始

from 从哪条开始, 序号从 0 开始

GET /bank/_search
{
  "query": {
    "match_all": {}
  },
  "from": 10,
  "size": 20
}
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值