我正在使用 Java API 尝试使用基本 Scala 程序的 Elasticsearch:
object TestES {
var node:Node = NodeBuilder.nodeBuilder.node
var client:Client = node.client
def insertDoc(id:String, doc:String) = {
client.prepareIndex("myindex", "test", id).
setSource(doc).execute.actionGet
}
def countHits(qry:String) = {
client.prepareSearch("myindex").setTypes("test").
setQuery(queryString(qry)).execute.actionGet.
getHits.getTotalHits
}
def waitForGreen = client.admin.cluster.prepareHealth().
setWaitForGreenStatus.execute.actionGet
def main(args: Array[String]): Unit = {
insertDoc("1", """{"foo":"bar"}""")
//waitForGreen
println(countHits("bar"))
node.close
}
}
这行得通,插入 + 查询在一秒钟内运行。如果我注释掉插入,我会得到以下异常:
Exception in thread "main" org.elasticsearch.action.search.SearchPhaseExecutionException:
Failed to execute phase [query], total failure;
shardFailures {[_na_][myindex][0]: No active shards}
如果我启用该waitForGreen
线路,它会再次运行,但运行两条线路需要半分钟以上。
这似乎很奇怪。在运行查询之前必须插入文档,还是有更好的方法?