索引的 Elasticsearch 查询和聚合

Elasticsearch query and aggregation on indices

我有多个 elasticsearch 索引,我想获得 doc_count 有多少文档与每个索引的查询匹配(即使没有文档与索引匹配)。我试过这个(使用 elasticsearch.js):

{
  index: 'one,or,many,indices,here',
  query: {
    query_string: {
      query: 'hello',
    },
  },
  aggs: {
    group_by_index: {
      terms: {
        field: '_index',
        min_doc_count: 0,
      },
    },
  },
  from: 0,
  size: 20,
};

这仅在我在 index 键上指定所有索引时才有效。但是,我并不总是希望在我的搜索结果中匹配所有索引中的文档。

所以我想出了:

{
  index: 'all,indices,here',
  query: {
    bool: {
      must: [
        {
          query_string: {
            query: 'hello',
          },
        },
        {
          terms: {
            _index: 'only,search,hits,indices,here',
          },
        },
      ],
    },
  },
  aggs: {
    group_by_index: {
      terms: {
        field: '_index',
        min_doc_count: 0,
      },
    },
  },
  from: 0,
  size: 20,
};

但随后我得到 doc_count: 0 匹配的索引,因为索引不在 bool 查询中。

如何获得所有索引的 doc_count 但不从不需要的索引中获得搜索匹配?

您需要将索引约束移动到 post_filter

{
  index: 'all,indices,here',
  query: {
    bool: {
      must: [
        {
          query_string: {
            query: 'hello',
          },
        },
      ],
    },
  },
  aggs: {
    group_by_index: {
      terms: {
        field: '_index',
        min_doc_count: 0,
      },
    },
  },
  post_filter: {
    terms: {
      _index: 'only,search,hits,indices,here',
    },
  },
  from: 0,
  size: 20,
};