在elasticsearch dsl查询语法文档的许多地方,在解释中跳过包装器json查询可能会减少文档大小。但是,当我浏览文档时,它一直令人困惑。 json查询中哪些内容可以或应该去哪些正式规则? 换句话说,我试图在所有弹性查询中找到共同的标准或模式,因为我需要构建一个内部api来查询弹性。是否有一个模板包含"query': {}
或"bool":{}
内的所有语法组件filter
,我可以在其中只需填写相关部分,它仍然运行?
答案 0 :(得分:7)
我也发现Elastic的DSL结构令人困惑,但是在运行了数百个查询后你就会习惯它。
以下是不同类型查询的一些(完整)示例,希望这有助于清除您可能遇到的一些问题,随时在评论中添加方案,我会添加更多示例。
这是标准查询的样子:
{
"query": {
"bool": {
"must": {
"match": {
"message": "abcd"
}
}
}
}
}
但是,这是过滤后的查询的样子,过滤弹性搜索时,您会发现结构发生了变化:
{
"query": {
"filtered": {
"filter": {
"term": {
"message": "abcd"
}
}
}
}
}
(Read more about the difference between Filters and Queries)
以下是包含过滤器和查询的查询的结果:
{
"query": {
"filtered": {
"filter": {
"term": {
"message": "abcd"
}
},
"query": {
"bool": {
"must": {
"match": {
"message2": "bbbb"
}
}
}
}
}
}
}
以下是运行多个条件的过滤器的方法:
{
"query": {
"filtered": {
"filter": {
"and": [
{
"term": {
"message": "abcd"
}
},
{
"term": {
"message2": "abcdd"
}
}
]
}
}
}
}
更复杂的过滤器:
{
"query": {
"filtered": {
"filter": {
"and": [
{
"term": {
"message": "abcd"
}
},
{
"term": {
"message2": "abcdd"
}
},
{
"or": [
{
"term": {
"message3": "abcddx"
}
},
{
"term": {
"message4": "abcdd2"
}
}
]
}
]
}
}
}
}
使用聚合的简单查询:
{
"query": {
"filtered": {
"filter": {
"term": {
"message": "abcd"
}
}
}
},
"aggs": {
"any_name_will_work_here": {
"max": {
"field": "metric1"
}
}
}
}
query_string
查询:
{
"query": {
"query_string": {
"default_field": "message",
"query": "this AND that"
}
}
}
使用DSL时需要考虑的其他事项:
size
参数,这将决定要返回的结果数量。如果你想要JUST doc计数,你可以使用"size": 0
,它不会得到任何结果,只有元数据。aggs
时尺寸参数有变化,在"size": 0
字段中设置aggs
会告诉ES获取所有聚合存储桶terms
,但range
例如有一些不同的结构。