如何从每个索引

时间:2016-03-24 13:57:35

标签: node.js search elasticsearch

我在Node Js中使用弹性搜索来查询多个索引,如何从每个索引中获取结果:

var esClient = new elasticsearch.Client({host: config.elasticsearch.host});

esClient.search({
    index: ["abc", "xyz"],
    type: ["abc", "xyz"],
    body: {
        query: {
            multi_match: {
                query: q,
                type: "cross_fields",
                analyzer: "ac_search_analyzer",
                operator: op,
                fields: ["a^4", "b^4", "c^2", "d", "e"]
            }
        }
    },
    _sourceInclude: ["a", "b", "c"],
    size: 10
}).then(function (resp) {
    //do something
}

现在我只从abc获得了所有10个结果,而xyz没有结果。我该怎么做才能说出来自abc的5个结果和来自xyz的5个结果。

1 个答案:

答案 0 :(得分:2)

您可以使用msearch在一次往返中查询每个索引的5个结果。

示例:

client.msearch({
        body: [
            { _index: "abc", type: "abc"},
            {
                query : { 
                    multi_match: {
                        query: q,
                        type: "cross_fields",
                        analyzer: "ac_search_analyzer",
                        operator: op,
                        fields: ["a^4", "b^4", "c^2", "d", "e"]
                    }
                }, 
                size : 5,
                _source : ["a", "b", "c"]
            },
            { _index: "xyz", type: "xyz"},
            {
                query : { 
                    multi_match: {
                        query: q,
                        type: "cross_fields",
                        analyzer: "ac_search_analyzer",
                        operator: op,
                        fields: ["a^4", "b^4", "c^2", "d", "e"]
                    }
                }, 
                size : 5,
                _source : ["a", "b", "c"]
            }
        ],
}).then(function (resp) {
  console.log(resp);
});

更新示例-2

msearch_query ={
                query : { 
                    multi_match: {
                        query: q,
                        type: "cross_fields",
                        analyzer: "ac_search_analyzer",
                        operator: op,
                        fields: ["a^4", "b^4", "c^2", "d", "e"]
                    }
                }, 
                size : 5,
                _source : ["a", "b", "c"]
            };
client.msearch({
        body: [
            { _index: "test", type: "test"},
            msearch_query,
            { _index: "new", type: "new"},
            msearch_query
        ],
}).then(function (resp) {
  console.log(resp);
});
相关问题