elasticsearch - 如何正确初始化Elasticsearch查询?

标签 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();
}

最佳答案

问题在于,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节省时间)

关于elasticsearch - 如何正确初始化Elasticsearch查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32253916/

相关文章:

python - 读取 CSV 并将数据上传到 Elasticsearch

elasticsearch - 带嵌套对象和脚本的Custom_Filters_Score

elasticsearch - 如何将elasticsearch-hadoop依赖项导入到spark脚本中

elasticsearch - 使用Akka Streams,我如何知道源何时完成?

filter - 将聚合限制为过滤器的结果

python - ElasticSearch 的 Celery 结果类型

elasticsearch - ElasticSearch如何设置geo_point

elasticsearch - 使用Elasticsearch,如何将功能分数应用于有条件具有属性的文档

elasticsearch - 如何在 Elasticsearch 中使嵌套字段中的子字段平坦?

amazon-web-services - AWS Elasticsearch 中的 "client node"?