ElasticSearch - 初试Query DSL

例子解析

GET /bank/_search
{
"query": { "match_all": {} },
"sort": { "balance": { "order": "desc" } }
}
  • 搜索索引为 bank
  • match_all 是简单的所有 document 进行匹配
  • sort 为排序以 balance 字段进行排序
  • { “order”: “desc” },排序方式降序
  • 默认 size 是 10
  • 默认 from 是 0

 例子 2

GET /bank/_search
{
"query": {
"match_all": {}
},
"_source": [
"account_number",
"balance"
]
}
  • _source 字段可以只取出想要的字段,如果字段没有则也不会返回

 搜索条件

GET /bank/_search
{
"query": { "match": { "account_number": 20 } }
}
  • match 后面跟具体的条件, 20 是数字所以对应 sql 里 = 20
GET /bank/_search
{
"query": { "match": { "address": "mill" } }
}
  • { “address”: “mill” } 对应 sql 里 like %mill%, 只有包含就可以,大小写不敏感
GET /bank/_search
{
"query": {
"match": {
"address": "mill lane"
}
}
}
  • like %mill% or like %lane% , 大小写不敏感.把这个  搜索条件进行了分词且是 || 的关系
GET /bank/_search
{
"query": {
"match_phrase": {
"address": "mill lane"
}
}
}
  • match_phrase 这个条件是局部的精确匹配. address 这个字段必须 _包含_ ‘mill lane’,大小写不敏感

bool query

GET /bank/_search
{
"query": {
"bool": {
"must": [
{ "match": { "address": "mill" } },
{ "match": { "address": "lane" } }
]
}
}
}

In the above example, the bool must clause specifies all the queries that must be true for a document to be considered a match.
这个例子和上面 match_phrase的例子的区别是,上面的还要求顺序,这个不要求

GET /bank/_search
{
"query": {
"bool": {
"should": [
{ "match": { "address": "mill" } },
{ "match": { "address": "lane" } }
]
}
}
}

the bool should clause specifies a list of queries either of which must be true for a document to be considered a match.
有一个满足就好了.
结果和下面这个一样

GET /bank/_search
{
"query": {
"match": {
"address": "mill lane"
}
}
}
GET /bank/_search
{
"query": {
"bool": {
"must_not": [
{
"match": {
"address": "mill"
}
},
{
"match": {
"address": "lane"
}
}
]
}
}
}

the bool must_not clause specifies a list of queries none of which must be true for a document to be considered a match.
都不能匹配

GET /bank/_search
{
"query": {
"bool": {
"must": [
{
"match": {
"age": "40"
}
}
],
"must_not": [
{
"match": {
"state": "ID"
}
}
]
}
}
}
  • 可以复合使用
  • This example returns all accounts of anybody who is 40 years old but doesn’t live in ID(aho):

bool query中使用filter

GET /bank/_search
{
"query": {
"bool": {
"must": {
"match": {
"firstname":"melissa"
}
},
"filter": {
"range": {
"balance": {
"gte": 20000,
"lte": 30000
}
}
}
}
}
}
  • range 一般用于数字或者日期