一尘不染

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

elasticsearch

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

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

如何解决这个问题?


阅读 274

收藏
2020-06-22

共1个答案

一尘不染

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

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

通常,您只是索引,当数据可用时,它便可用。这称为最终一致性。在此期间(秒),用户可能无法使用它进行搜索。通常这不是问题。

如果这是一个问题,那么您将必须做一些技巧,就像我们在elastic4s的单元测试中所做的那样,在这里您要不断“计数”,直到获得正确数量的文档为止。

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

client.execute {
  refresh index "indexname"
}

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

2020-06-22