执行查询

source:https://www.elastic.co/guide/en/elasticsearch/reference/6.4/getting-started-search.html

现在我们了解了一些简单的查询参数,我们接下来研究一些queryDSL,首先我们看一下返回文档的内容。

默认情况下,json文档会返回搜索结果的不同部分,如果不想返回所有,可以通过指定_source来指定返回部分。

下面的例子展示了返回指定的两个字段

curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": { "match_all": {} },
"_source": ["account_number", "balance"]
}
'

注意这个例子减少了_source中字段的返回,只返回我们在_source中指定的两个字段。

如果我们对比一下SQL语句,上面的查询与SQL的select from 操作类似。

现在我们跳过query的查询,开始学习match查询,可以认为这个是搜索查询中的基本字段搜索

一个返回account_number为20的查询:

curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": { "match": { "account_number": 20 } }
}
'

指定address为'mill'的查询

curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": { "match": { "address": "mill" } }
}
'

返回address等于'mill'或者'lane'的查询

curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": { "match": { "address": "mill lane" } }
}
'

返回address包含'mill'或者'lane'的查询

curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": { "match_phrase": { "address": "mill lane" } }
}
'

现在介绍一下bool query查询,bool允许我们通过布尔逻辑将小的查询组合成较大查询

下面的例子是返回包括'mill'和'lane'的两个组合查询

curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"bool": {
"must": [
{ "match": { "address": "mill" } },
{ "match": { "address": "lane" } }
]
}
}
}
'

上面的例子中,bool查询要求必须满足上面的两个条件

下面这例子是返回address中包含'mill'或者'lane'的两个查询组合

curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"bool": {
"should": [
{ "match": { "address": "mill" } },
{ "match": { "address": "lane" } }
]
}
}
}
'

上面示例中,bool should指定返回符合其中任何一项条件的数据组合

 

下面的示例是返回结果既不包含'mill'也不包含‘lane’的查询

curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"bool": {
"must_not": [
{ "match": { "address": "mill" } },
{ "match": { "address": "lane" } }
]
}
}
}
'

上面的示例中。must_not返回不符合上面所有条件的结果集

我们可以通过在一个查询中同时使用must should must_not来对比bool查询的返回,

我们同样可以在一个布尔查询中对上面的三种不同的查询进行组合,组成更加复杂的多层布尔逻辑查询。

下面的示例返回40岁并且没有活跃账号ID的用户数据

curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"bool": {
"must": [
{ "match": { "age": "40" } }
],
"must_not": [
{ "match": { "state": "ID" } }
]
}
}
}
'

 

posted @ 2019-11-25 12:14  Aemnprsu_wx  阅读(146)  评论(0编辑  收藏  举报