我编写了一个程序,该程序插入一个元素,然后搜索商店中的所有元素。因此,每次程序运行时,它都会发现另一个元素。我希望能够注释掉插入内容,并且仍然可以运行程序,只需找到已插入的内容即可。但是,无论何时,我都会得到一个异常“无法执行阶段[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/