2

这是我用来进行简单搜索的小代码:

import com.sksamuel.elastic4s.{ElasticsearchClientUri, ElasticClient}
import com.sksamuel.elastic4s.ElasticDsl._
import org.elasticsearch.common.settings.ImmutableSettings

object Main3 extends App {
  val uri = ElasticsearchClientUri("elasticsearch://localhost:9300")
  val settings = ImmutableSettings.settingsBuilder().put("cluster.name", "elasticsearch").build()
  val client = ElasticClient.remote(settings, uri)
  if (client.exists("bands").await.isExists()) {
    println("Index already exists!")
    val num = readLine("Want to delete the index? ")
    if (num == "y") {
      client.execute {deleteIndex("bands")}.await
    } else {
      println("Leaving this here ...")
    }
  } else {
    println("Creating the index!")
    client.execute(create index "bands").await
    client.execute(index into "bands/artists" fields "name"->"coldplay").await
    val resp = client.execute(search in "bands/artists" query "coldplay").await
    println(resp)
  }
  client.close()
}

这是我得到的结果:

Connected to the target VM, address: '127.0.0.1:51872', transport: 'socket'
log4j:WARN No appenders could be found for logger (org.elasticsearch.plugins).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Creating the index!
{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 0,
    "max_score" : null,
    "hits" : [ ]
  }
}
Disconnected from the target VM, address: '127.0.0.1:51872', transport: 'socket'

Process finished with exit code 0

创建索引并将文档添加到该索引运行良好,但简单的搜索查询没有给出任何结果。我什至在 Sense 上检查了这一点。

GET bands/artists/_search
{
  "query": {
    "match": {
      "name": "coldplay"
    }
  }
}

{
   "took": 4,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 1,
      "max_score": 0.30685282,
      "hits": [
         {
            "_index": "bands",
            "_type": "artists",
            "_id": "AU21OYO9w-qZq8hmdTOl",
            "_score": 0.30685282,
            "_source": {
               "name": "coldplay"
            }
         }
      ]
   }
}

如何解决这个问题?

4

1 回答 1

3

我怀疑正在发生的事情是您在代码中的索引操作之后直接进行搜索。但是在弹性搜索中,文档还没有准备好立即进行搜索。请参阅此处的刷新间隔设置。(因此,当您使用其余客户端时,由于您必须在选项卡之间手动滑动等事实,您正在等待几秒钟)。

您可以通过在索引后放置一个 Thread.sleep(3000) 来快速测试这一点。如果这证实了它然后工作,那么你需要考虑你想如何编写你的程序。

通常你只是索引,当数据可用时,它就可用。这称为最终一致性。同时(秒)用户可能无法搜索它。这通常不是问题。

如果这是一个问题,那么你将不得不像我们在 elastic4s 的单元测试中那样做一些技巧,在这些技巧中你一直“计数”直到你得到正确数量的文档。

最后,您还可以通过调用手动“刷新”索引以加快速度

client.execute {
  refresh index "indexname"
}

但这通常仅在您关闭批量插入的自动刷新时使用。

于 2015-06-02T20:39:46.643 回答