48.Query DSL

主要知识点

1Query DSL的理解及基本语法

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

   

一、Query DSL的理解

Query DSL的查询形式如下:

GET /_search

{

"query": {

"match_all": {}

}

}

37小节中我们学到到query string 的语法,这里学习另外一种搜索语法,

Query DSL(Domain Specific Language),这个方法是在"query"字段中定义我们要搜索的内容,包括匹配的方式等信息。

   

二、Query DSL的基本语法

1

{

QUERY_NAME: {

ARGUMENT: VALUE,

ARGUMENT: VALUE,...

}

}

2

{

QUERY_NAME: {

FIELD_NAME: {

ARGUMENT: VALUE,

ARGUMENT: VALUE,...

}

}

}

   

示例:

   

GET /test_index/test_type/_search

{

"query": {

"match": {

"test_field": "test"

}

}

}

查询test_field这个字段中必修包含test

三、如何组合多个搜索条件

1、先构造数据

PUT /website/article/1

{

"title":"es",

"content":"I love es",

"author_id":111

}

PUT /website/article/2

{

"title":"python",

"content":"I love python",

"author_id":112

}

PUT /website/article/3

{

"title":"scrapy",

"content":"I love scrapy",

"author_id":113

}

2、提供需求

title必须包含es,content可以包含es也可以不包含,author_id必须不为113

3、书写es bool查询语句

GET /website/article/_search

{

"query": {

"bool": {

"must": [

{"match": {

"title": "es"

}}

],

"should": [

{"match": {

"content": "es"

}}

],

"must_not": [

{"match": {

"author_id": "113"

}}

]

}

}

}

执行结果如下:

{

"took": 269,

"timed_out": false,

"_shards": {

"total": 5,

"successful": 5,

"failed": 0

},

"hits": {

"total": 1,

"max_score": 0.5408423,

"hits": [

{

"_index": "website",

"_type": "article",

"_id": "1",

"_score": 0.5408423,

"_source": {

"title": "es",

"content": "I love es",

"author_id": 111

}

}

]

}

}

   

另一个较为复杂的示例

GET /test_index/_search

{

"query": {

"bool": {

"must": { "match": { "name": "tom" }},

"should": [

{ "match": { "hired": true }},

{ "bool": {

"must": { "match": { "personality": "good" }},

"must_not": { "match": { "rude": true }}

}}

],

"minimum_should_match": 1

}

}

}

   

四、延伸阅读

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html

   

   

原文地址:https://www.cnblogs.com/liuqianli/p/8471369.html