执行搜索
现在我们已经看到了一些基本的查询参数, 让我们更深入一下查询DSL. 让我们先看看返回的文档的字段, 默认情况下, 完整的JSON文档作为所有搜索的一部分返回. 这被称之为source(搜索hits中的_source字段). 如果我们不想要返回完整的source文档. 我们可以从返回的source文档请求部分字段.
下面这个例子展示了如何从搜索中只返回2个字段, account_number和balance(_source中).
GET /bank/_search
{
"query": { "match_all": {} },
"_source": ["account_number", "balance"]
}
注意上面的例子只是减少了_source字段. 它仍然会返回一个名为_source的字段, 但是其中只包含account_number和balance字段.
如果你有使用SQL的经验, 上面的例子十分类似于SQL语言中的SELECT FROM过滤查询字段.
现在我们看看查询部分, 在此之前, 我们已经看到如何使用match_all去匹配所有文档. 现在我们引入一个新的查询叫做match query, 这可以被当做是一种基本字段的查询(即对特定字段或字段集的搜索).
下面的例子返回account_number为20的文档:
GET /bank/_search
{
"query": { "match": { "account_number": 20 } }
}
下面这个例子返回所有address字段包含"mill"的文档:
GET /bank/_search
{
"query": { "match": { "address": "mill" } }
}
下面这个例子返回address字段包含"mill"或者"lane"的文档:
GET /bank/_search
{
"query": { "match": { "address": "mill lane" } }
}
下面这个例子是match的变体(match_phrase), 他返回adress字段包含"mill lane"短语的文档:
GET /bank/_search
{
"query": { "match_phrase": { "address": "mill lane" } }
}
我们现在来介绍一下布尔查询. 布尔查询允许我们通过boolean逻辑来把小的查询组合成更大的查询.
下面这个例子组合了2个查询, 返回了address包含"mill"和"lane"的文档:
GET /bank/_search
{
"query": {
"bool": {
"must": [
{ "match": { "address": "mill" } },
{ "match": { "address": "lane" } }
]
}
}
}
在上面的例子中, bool must子句指定了所有查询必须为true才会返回匹配,.
相对的, 这个例子组合了2个match查询, 返回了address包含mill或lane的文档:
GET /bank/_search
{
"query": {
"bool": {
"should": [
{ "match": { "address": "mill" } },
{ "match": { "address": "lane" } }
]
}
}
}
上面的例子中, bool should子句指定了一系列查询条件, 只要有一个返回true, 文档就匹配返回.
这个例子组合了2个match查询, 并且返回所有address不包含mill和lane的文档:
GET /bank/_search
{
"query": {
"bool": {
"must_not": [
{ "match": { "address": "mill" } },
{ "match": { "address": "lane" } }
]
}
}
}
上面的例子中, bool must_not子句指定了一组查询条件, 必须所有条件都不匹配, 才会返回文档.
我们可以同时结合must, should和must_not子句在一个bool查询中. 并且, 我们可以在这些bool子句中结合bool查询, 已达到复杂逻辑查询的目的.
这个例子返回了所有40并且没有生活在ID的文档:
GET /bank/_search
{
"query": {
"bool": {
"must": [
{ "match": { "age": "40" } }
],
"must_not": [
{ "match": { "state": "ID" } }
]
}
}
}