Elasticsearch对索引的查询和聚合

问题描述 投票:0回答:1

我有多个弹性搜索索引,我想得到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但不会从不需要的指数获得搜索命中?

elasticsearch elasticsearch-aggregation
1个回答
1
投票

您需要将索引约束移动到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,
};
© www.soinside.com 2019 - 2024. All rights reserved.