如何正确初始化Elasticsearch的查询?

时间:2015-08-27 15:43:24

标签: elasticsearch

我编写了一个插入元素的程序,然后搜索商店中的所有元素。因此,每次程序运行时它都会找到一个元素。我希望能够注释掉插入并仍然运行程序,只需查找已经插入的内容。每当我这样做时,我得到一个异常“无法执行阶段[query_fetch],所有分片都失败了”。有什么想法吗?

假设:插入元素会在我的节点上进行某种隐式初始化。但是,我正在查看ES源代码,我无法弄清楚它会是什么。

try (Node node = NodeBuilder.nodeBuilder().clusterName("tesssst").build().start()) {
    try (Client client = node.client()) {

        //insert an entry; if this part is removed, the program crashes
        client.prepareIndex("movies", "movie", UUID.randomUUID().toString()).setSource(
            "{\"title\": \"Lawrence of Arabia\",\"director\": \"David Lean\",\"year\": 1962,\"genres\":"
            + " [\"Adventure\", \"Biography\", \"Drama\"]}").execute().actionGet();

        //search all entries
        System.out.println("***************");
        SearchResponse response = client.prepareSearch("movies")
            .setTypes("movie")
            .setSearchType(SearchType.QUERY_AND_FETCH)
            .setFrom(0).setSize(60).setExplain(true)
            .execute()
            .actionGet();
        SearchHit[] results = response.getHits().getHits();
        System.out.println("Current results: " + results.length);
        for (SearchHit hit : results) {
            System.out.println("------------------------------");
            Map<String, Object> result = hit.getSource();
            System.out.println(result);
        }
        System.out.println("***************");

        client.close();
    }
    node.close();
}

1 个答案:

答案 0 :(得分:1)

问题是Elasticsearch没有足够的时间来启动,但初始插入给了它足够的时间。只需添加适当的等待即可修复它:

final ClusterHealthRequest clusterHealthRequest = new ClusterHealthRequest("movies")
        .timeout(TimeValue.timeValueSeconds(60)).waitForGreenStatus();
final ClusterHealthResponse clusterHealth = client.admin().cluster()
        .health(clusterHealthRequest).actionGet();
if (clusterHealth.isTimedOut()) {
    System.out.println("ElasticSearch cluster health timed out");
} else {
    System.out.println("ElasticSearch cluster health: Status "
           + clusterHealth.getStatus().name() + "; " + clusterHealth.getNumberOfNodes()
           + " nodes; " + clusterHealth.getActiveShards() + " active shards.");
}

(如果您的标准较低,则可以使用waitForYellowStatus

节省时间