本文介绍了使用elastic4s搜索结果为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个我使用的小代码来做一个简单的搜索:

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

对象Main3扩展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 (要删除索引?)
if(num ==y){
client.execute {deleteIndex(bands)} await
} else {
println(离开这里...)
}
} else {
println(创建索引!)
client.execute(创建索引 ).await
client.execute(index intobands / art istsfields - >coldplay)await
val resp = client.execute(在bands / artists查询coldplay中搜索)await
println(resp)
}
client.close()
}

这是结果我得到:

 连接到目标VM,地址:'127.0.0.1:51872',transport:'socket'
log4j:WARN没有找到记录器(org.elasticsearch.plugins)的appender。
log4j:WARN请正确初始化log4j系统。
log4j:WARN有关详细信息,请参阅http://logging.apache.org/log4j/1.2/faq.html#noconfig。
创建索引!
{
take:1,
timed_out:false,
_shards:{
total:5,
:5,
failed:0
},
hits:{
total:0,
max_score:null,
hits:[]
}
}
与目标VM断开连接,地址:'127.0.0.1:51872',transport:'socket'

处理完成退出代码0

创建索引并向此索引添加文档运行正常,但一个简单的搜索查询没有结果。我甚至在感觉中检查了这个。

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

给出

  {
taken:4 ,
timed_out:false,
_shards:{
total:5,
success:5,
failed b $ b},
hits:{
total:1,
max_score:0.30685282,
hits:[
{
_index:bands,
_type:artists,
_id:AU21OYO9w-qZq8hmdTOl,
_score:0.30685282,
_source:{
name:coldplay
}
}
]
}
}
解决方案

>我怀疑发生了什么事情是你正在搜索直接r代码中的索引操作。然而,在弹性搜索文档中,还没有准备好立即进行搜索。请参见。 (所以当你使用休息的客户端时,你会等待几秒钟,因为你必须手动在标签之间轻弹等)。



你可以测试这个在索引后放置一个Thread.sleep(3000),如果这样确认它然后工作,那么你需要考虑如何写你的程序。



通常您只需索引,数据可用时,则可用。这被称为最终一致性。在此期间(秒),用户可能无法搜索。这通常不是一个问题。



如果这是一个问题,那么你将不得不做一些技巧,像我们在弹性4的单元测试中,你保持计数



最后,您还可以通过调用

$ b手动刷新索引来加快速度
$ b

  client.execute {
刷新索引indexname
}

但是通常只有当您关闭批量插入的自动刷新时才会使用。


This is a small code I am using to do a simple search:

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()
}

This is result that I get:

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

Creation of an index and adding document to this index is running fine but a simple search query is giving no result. I even checked this on Sense.

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

gives

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

How to solve this issue?

解决方案

I suspect what is happening is that you are doing the search straight after the index operation in your code. However in elasticsearch documents are not ready for search immediately. See refresh interval setting here. (So when you use the rest client, you are waiting a few seconds by virtue of the fact you have to manually flick between tabs, etc).

You could test this quickly by putting a Thread.sleep(3000) after the index. If that confirms it then works, then you need to think about how you want to write your program.

Normally you just index, and when the data is available, then its available. This is called eventual consistency. In the meantime (seconds) users might not have it available to search. That's usually not a problem.

If it IS a problem, then you will have to do some tricks like we do in the unit tests of elastic4s where you keep 'count'ing until you get back the right number of documents.

Finally, you can also manually 'refresh' the index to speed things up, by calling

client.execute {
  refresh index "indexname"
}

But that's usually only used when you turn off the automatic refreshing for bulk inserts.

这篇关于使用elastic4s搜索结果为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 06:06