0

我正在使用 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线路,它会再次运行,但运行两条线路需要半分钟以上。

这似乎很奇怪。在运行查询之前必须插入文档,还是有更好的方法?

4

1 回答 1

0

运行查询不需要插入文档,但需要创建索引。当你插入一个文档并且索引不存在时,它会被自动创建。

如果您想避免创建文档,您可以使用 API 仅创建索引:

client.admin.indices.prepareCreate("myindex").execute.actionGet
于 2013-06-17T09:48:18.203 回答