四十七、Elasticsearch初识搜索引擎-Query DSL

1、Query DSL基础语法

(1)查询全部index下的全部type的全部document

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

(2)查询test_index下的全部type的全部document

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

(3)查询test_index下的test_type下document的test_field字段包含test的

GET /test_index/test_type/_search
{
  "query": {
    "match": {
      "test_field": "test"
    }
  }
}

语法不在重复说明,之前的文章已经说的很明白的。

2、如何组合多个搜索条件?

关键字:bool

需求:搜索title必须包含elasticsearch,content可以包含elasticsearch也可以不包含,author_id必须不为111的document

(1)数据准备

PUT /website/article/1
{
  "title" : "my elasticsearch article",
  "content" : "es is very good",
  "author_id" : 110
}

PUT /website/article/2
{
  "title" : "my hadoop article",
  "content" : "es is very good",
  "author_id" : 111
}

PUT /website/article/3
{
  "title" : "my elasticsearch article",
  "content" : "elasticsearch is very bad",
  "author_id" : 111
}

进行搜索

GET /website/article/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "title": "Elasticsearch"
          }
        }
      ],
      "should": [
        {
          "match": {
            "content": "Elasticsearch"
          }
        }
      ],
      "must_not": [
        {
          "match": {
            "author_id": "111"
          }
        }
      ]
    }
  }
}

返回结果:

{
  "took": 11,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 0.25316024,
    "hits": [
      {
        "_index": "website",
        "_type": "article",
        "_id": "1",
        "_score": 0.25316024,
        "_source": {
          "title": "my elasticsearch article",
          "content": "es is very good",
          "author_id": 110
        }
      }
    ]
  }
}

假设should里面又来个bool{must:{match}}这种的,那么代表这个must也是可有可无的,因为他最外层是should

若有兴趣,欢迎来加入群,【Java初学者学习交流群】:458430385,此群有Java开发人员、UI设计人员和前端工程师。有问必答,共同探讨学习,一起进步!
欢迎关注我的微信公众号【Java码农社区】,会定时推送各种干货:


四十七、Elasticsearch初识搜索引擎-Query DSL_第1张图片
qrcode_for_gh_577b64e73701_258.jpg

你可能感兴趣的:(四十七、Elasticsearch初识搜索引擎-Query DSL)