如何在Elasticsearch中过滤子索引以进行聚合?

nip*_*eco 5 elasticsearch

我查询使用通配符(索引interactive*),以获得这两个指数的所有文件interactive-foo*interactive-bar*.

对于我的一些聚合,所有指数都是相关的,但对于其他指数只有interactive-foo* OR interactive-bar*.所以我只想过滤聚合中的这些"子指标".

GET _search
{
  "query":{
    "bool": {
      "must": [
        {
          "range": {
            "timestamp": {
              "gte": "2017-08-01 00:00:00",
              "lte": "2017-08-31 23:59:59"
            }
          }
        },
        {
          "match": {
            "key": "SOME_KEY"
          }
        }
      ]
    }
  },
  "size":0,
  "aggs": {
    // This one should be filtered and just count for interactive-bar*
    "bar_count": {
      "value_count": {
        "field": "SOME_FIELD"
      }
    },
    // This one should be filtered and just count for interactive-foo*
    "foo_count": {
      "value_count": {
        "field": "SOME_FIELD"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Val*_*Val 3

您可以使用filter这样的聚合:

{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "timestamp": {
              "gte": "2017-08-01 00:00:00",
              "lte": "2017-08-31 23:59:59"
            }
          }
        },
        {
          "match": {
            "key": "SOME_KEY"
          }
        }
      ]
    }
  },
  "size": 0,
  "aggs": {
    "bar_count": {
      "filter": {
        "indices": {
          "indices": ["interactive-bar-*"]
        }
      },
      "aggs": {
        "bar_count": {
          "value_count": {
            "field": "SOME_FIELD"
          }
        }
      }
    },
    "foo_count": {
      "filter": {
        "indices": {
          "indices": ["interactive-foo-*"]
        }
      },
      "aggs": {
        "foo_count": {
          "value_count": {
            "field": "SOME_FIELD"
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

请注意,该indices查询在 ES 5.0 中已被弃用。您应该做的是在字段上使用terms查询_index并列出您想要包含在聚合中的所有索引,如下所示:

  "size": 0,
  "aggs": {
    "bar_count": {
      "filter": {
        "terms": {
          "_index": ["interactive-foo-2017.08.14", "interactive-foo-2017.08.15"]
        }
      },
      "aggs": {
        "bar_count": {
          "value_count": {
            "field": "SOME_FIELD"
          }
        }
      }
    },
    "foo_count": {
      "filter": {
        "terms": {
          "_index": ["interactive-bar-2017.08.14", "interactive-bar-2017.08.15"]
        }
      },
      "aggs": {
        "foo_count": {
          "value_count": {
            "field": "SOME_FIELD"
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)