获得零会导致使用elastic4s进行搜索

时间:2015-06-02 17:12:55

标签: scala elasticsearch 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"
            }
         }
      ]
   }
}

如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

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

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

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

如果这是一个问题,那么你将不得不做一些技巧,就像我们在elastic4s的单元测试中所做的一样,你会保持计数,直到你找回正确数量的文件。

最后,您还可以手动“刷新”'通过调用

加快速度的索引
client.execute {
  refresh index "indexname"
}

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