使用 elastic4s 在搜索中得到零结果

Getting zero results in search using elastic4s

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

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"
            }
         }
      ]
   }
}

如何解决这个问题?

我怀疑发生的事情是您在代码中的索引操作之后直接进行搜索。然而,在 elasticsearch 文档中并没有立即准备好进行搜索。请参阅此处 refresh interval setting。 (因此,当您使用其余客户端时,由于您必须在选项卡之间手动轻弹等事实,您需要等待几秒钟)。

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

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

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

最后,您还可以手动 'refresh' 索引来加快速度,方法是调用

client.execute {
  refresh index "indexname"
}

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