本篇教程主要给大家讲解elasticsearch中的查询
elasticsearch是功能非常强大的搜索引擎,使用它的目的是为了快速的查询需要的数据。
查询分类:
基本查询:使用elasticsearch内置查询条件进行查询
组合查询:把多个查询组合在一起进行复合查询
过滤查询:查询的同时,通过filter条件,在不影响打分的情况下筛选数据
1.match查询和term查询的区别:
term会拿着传递进来的值,不会做任何处理(term查询中对传递进来的参数不会做分词处理,直接当做一个整体,并且不会做倒排索引)
match查询会将传递进来的参数进行一下分词的处理
terms查询:在执行搜索的时候传递进来一个array数组进来,于是只要是含有该数组中的内容,该数据都会被查询出来
下面先添加几条elasticsearch中的数据:
#接下来我们使用term查询
GET lagou/job/_search
{
"query":{
"term":{
"title":"python"
}
},"from":0,"size":3
}
#还有match查询
GET lagou/job/_search
{
"query":{
"match":{
"title":"python"
}
},"from":0,"size":3
}
#使用match_all 这个方法来查询lagou下面的所有的记录
GET lagou/_search{
"query":{
"match_all":{}
}
}
#multi_match查询
#比如可以指定多个字段
#比如查询title和desc这两个字段里面包含pythono的关键词文档,下面的title^3代表的意思是权重,在搜索出了结果之后,elasticsearch会为系统打分_score,权重高的数据会排列在前面。
GET lagou/_search
{
"query":{
"multi_match":{
"query":"python",
"fields":["title^3","desc"]
}
}
}
#短语查询 match_phrase
#使用这种短语查询,在查询的时候会给传入的参数进行分词的操作,query中传入句子,slop中传入的参数可以指定两个分词之间的间隔距离,当大于这个间隔 6 的时候查询不出来。
GET /lagou/_search{
"query":{
"match_phrase":{
"title":{
"query":"linux工程师",
"slop":6
}
}
}
}
#通过sort查询可以把结果进行排序(下面的例子中查询出所有的结果并且按照降序进行排列,把查询出的所有的数据按照 comments进行降序的排列
GET lagou/_search{
"query":{
"match_all":{}
},
"sort":[
{
"comments":{
"order":"desc'
}
}
]
}
#查询范围
#range boost代表的是权重的意思,查询comment>=10 <=50的数
GET lagou/_search
{
"query":{
"range":{
"comments":{
"gte":10,
"lte":20,
"boost":2.0
}
}
}
}
#wildcard查询支持字符串里面有通配符
GET lagou/_search
{
"query":{
"wildcard":
{
"title":{
"value":"pyth*n",
"boost":2.0
}
}
}
}
#elasticsearch中使用的非常多的bool查询
#老版本的filter已经被bool替换
#用 bool must should must_not 来完成,格式如下
{
"bool":[],
"must":[],
"should":[],
"must_not":[],
}
#接下来讲解下elasticsearch中的bool查询
#老版本的filter已经被bool替换
#用bool查询包括 must should must_not filter来完成,格式如下:
bool:{
"filter":[],
"must":[],
"should":[],
"must_not":[],
}
#简单的过滤查询
#最简单的filter查询
#select * from testjob where comments = 20
#filter薪资为20k的工作,这里要不要must都可以
GET lagou/testjob/_search{
"query":{
"bool":{
"must":{
"match_all":{}
}
"filter":{
"term":{
"salary":20
}
}
}
}
}
#select * from testjob where title = "Python" #这个地方需要注意的地方是,当使用term查询的时候,由于term会给系统做倒排索引,
所以当在查询的输入参数中出现大写符号,如下面的"title":"Python"的时候,会出现查不出来值的情况,但是这里换成是match查询则不出
出现这种状况
GET lagou/testjob/_search
{
"query":{
"bool":{
"must":{
"match_all":{}
},
"filter": {
"term":{
"title":"Python"
}
}
}
}
}
#查看elasticsearch中分析器给出的分析结果(analyzer当中可用的参数"ik_max_word","ik_smart")
这里对比一下 ik_max_word 和 ik_smart中分词的区别
ik_max_word会将词语分词到尽可能多 下面的句子会被分解成 "python" ,"网络","络" ,"开发","发","工程师","工程","师"
而ik_smart相对就分词的更少一些: "python" ,"网络","开发","工程师"
GET _analyze
{
"analyzer":"ik_max_word",
"text":"python网路开发工程师"
}
#通过过滤查询,可以做组合过滤查询
#select * from testjob where (salary=20 or title=python) AND (salary != 30)
#查询你薪资等于20k的工作为python的工作表,排除价格为30k的
GET lagou/testjob/_search
{
"query":{
"bool":{
"should":[
{"term":{"salary":20}},
{"term":{"title":"python"}}
],
"must_not":{
"term":{"price":30}
}
}
}
}