Elasticsearch Index Data在查询中给出错误的结果

时间:2018-01-18 04:38:01

标签: javascript node.js reactjs elasticsearch

我正在尝试使用Elasticsearch为我的反应式网络应用创建全文搜索,但它不会在查询中返回所有结果。我认为我在批量方法中犯了一些错误,但我无法理解我做错了什么。 我的代码是:

// Declare variable to contain body of JSON data for loading to ElasticSearch

                    let br = [];

// Function to create body for loading to ElasticSearch
                    function create_bulk (bulk_request) {
                        let obj;

                        for (let i = 0; i < res.length; i++) {
                            obj = res[i];
                            // Insert header of record
                            bulk_request.push({index: {_index: 'tweet', _type: 'tweet', _id: i+1}});
                            bulk_request.push(obj);
                        }
                        return bulk_request;
                    }

// Call function to get body for loading
                    create_bulk(br);

// Standard function of ElasticSearch to use bulk command
                    client.bulk(
                        {
                            body : br
                        }, function (err, resp) {
                            console.log(err);
                        });

                    client.search({
                        index: 'tweet',
                        type: 'tweet',
                        body: {
                            query: {
                                match: {"text" : "new york" }
                            },
                        }
                    },function (error, response,status) {
                        if (error){
                            console.log("search error: "+error)
                        }
                        else {
                            console.log("--- Response ---");
                            console.log(response);
                            console.log("--- Hits ---");
                            response.hits.hits.forEach(function(hit){
                                console.log(hit);
                            })
                        }
                    });

Data Sample是一个JSON数据数组:

{date: "2014-06-04 11:30:07", text: "New York Today: Honoring our Civil Servants t.co/Lhz9fgt2FW", user_id: "nytimes "}

1 个答案:

答案 0 :(得分:1)

在批量通话和搜索通话之间,您需要调用刷新以确保所有索引数据都可供搜索。

                client.bulk(
                    {
                        refresh: true,            <--- add this
                        body : br
                    }, function (err, resp) {
                        console.log(err);

                        client.search({...})      <--- and make your search call only when the bulk returns

                    });