elasticsearch高级查询整理

深碍√TFBOYSˉ_ 2022-03-18 11:40 316阅读 0赞

#子条件查询: 子条件查询又分为Query context 和 Filter context

#符合条件查询: 以一定的逻辑组合子条件查询

#子条件查询

Query Context

在查询过程中,除了判断文档是否满足查询条件外,ES还会计算一个_source来表示匹配的程度,旨在判断文档与查询条件的匹配的有多好。返回值有一个Score分数来标识。
常用查询:全文本查寻(文本类型)、字段级别查询(数组、日期…)

全文本查

模糊匹配,会把关键字分开搜索,不会当成一个整体。例如搜索Elastic搜索,会匹配Elastic和搜索两个关键字。

  1. {
  2. "query":{
  3. "match":{
  4. "author":"大哥"
  5. }
  6. }
  7. }

短语匹配,把关键字当一个不可分的短语

  1. {
  2. "query":{
  3. "match_phrase":{
  4. "title":"Elastic搜索"
  5. }
  6. }
  7. }

多字段匹配,寻找author和title包括关键字的

  1. {
  2. "query":{
  3. "multi_match":{
  4. "query":"Elastic搜索",
  5. "filter": ["author","title"]
  6. }
  7. }
  8. }

语法查询

  1. {
  2. "query":{
  3. "query_string": {
  4. "query":"Elastic搜索 AND 入门"
  5. }
  6. }
  7. }

多条件语法

  1. {
  2. "query":{
  3. "query_string": {
  4. "query":"(Elastic搜索 AND 入门) OR Python"
  5. }
  6. }
  7. }

多条件语法多字段查

  1. {
  2. "query":{
  3. "query_string": {
  4. "query":"Elastic OR Python",
  5. "fields":["title","author"]
  6. }
  7. }
  8. }

按字段查

关键词term

  1. {
  2. "query":{
  3. "term":{
  4. "word_count":1000
  5. }
  6. }
  7. }

按范围查,关键词:range

  1. {
  2. "query":{
  3. "range":{
  4. "word_count":{
  5. "gte":1000, //后面这个e就是equal
  6. "lte":2000
  7. }
  8. }
  9. }
  10. }

按日期

  1. {
  2. "query":{
  3. "range":{
  4. "date":{
  5. "gte":"2017-1-1", //后面这个e就是equal
  6. "lte":"now"
  7. }
  8. }
  9. }
  10. }

Filter Context

关键词:bool,只关心查询是true or false,不关心查询好的程度。

  1. {
  2. "query": {
  3. "bool":{
  4. "filter":{
  5. "term":{
  6. "word_count":1000
  7. }
  8. }
  9. }
  10. }
  11. }

#符合条件查询

组合上述子条件

固定分数查询

关键词:constant_score

  1. {
  2. "query":{
  3. "constant_score":{ //只支持filter,不支持match
  4. "filter":{
  5. "match":{
  6. "title":"Elastic搜索"
  7. }
  8. },
  9. "boost":2 //指定分数为2
  10. }
  11. }
  12. }

布尔查询

关键词should

  1. {
  2. "query":{
  3. "should":[
  4. {
  5. "match":{
  6. "author":"大哥"
  7. }
  8. },
  9. {
  10. "match":{
  11. "title":"Elastic搜索"
  12. }
  13. }
  14. ]
  15. }
  16. }

关键词must

  1. {
  2. "query":{
  3. "bool":{
  4. "must":[
  5. {
  6. "match":{
  7. "author":"大哥"
  8. }
  9. },
  10. {
  11. "match":{
  12. "title":"Elastic搜索"
  13. }
  14. }
  15. ],
  16. "filter":[
  17. "term":{
  18. "word_count":1000
  19. }
  20. ]
  21. }
  22. }
  23. }

关键词must_not

  1. {
  2. "query":{
  3. "bool":{
  4. "must_not":{
  5. "term":{
  6. "author":"郑联军"
  7. }
  8. }
  9. }
  10. }

发表评论

表情:
评论列表 (有 0 条评论,316人围观)

还没有评论,来说两句吧...

相关阅读