繁体   English   中英

更新后如何从elasticsearch返回文档?

[英]How return document from elasticsearch after update?

我正在尝试更新几个文档字段,并在更新后返回完整文档。 我用elastic4s 1.3.4, elasticsearch 1.4.3(如服务器)。

这是一个代码:

import scala.concurrent.ExecutionContext.Implicits.global
object ElasticsearchTester extends App {
  private val settings: Settings = ImmutableSettings.settingsBuilder().put("cluster.name", "clustername").build()
  private val client: ElasticClient = ElasticClient.remote(settings, ("localhost", 9300))

  val initial = """
    |{
    |   "name":"jojn",
    |   "surname":"olol"
    |}
  """.stripMargin

  val updateString = """
    |{
    |   "surname":"123",
    |   "global": {
    |     "new":"fiedl"
    |   }
    |}
  """.stripMargin

  import com.sksamuel.elastic4s.ElasticDsl._
  val future = client.execute {
    create index "my_index"
  }.flatMap { r=>
    client.execute {
      index into "my_index/user" doc StringDocumentSource(initial)
    }.flatMap { re=>
      println("Ololo indexed is: " + initial)
      println("Ololo indexed id: " + re.getId)
      client.execute {
        update id re.getId in "my_index/user" doc StringDocumentSource(updateString) docAsUpsert true params  ("fields" -> "_source")
      }.map{res=>
        println("Ololo result is: " + res.getGetResult.sourceAsString())

      }
    }
  }

  Await.result (future, 20.seconds)
  println("Ololo ok")
}

为什么我在res.getGetResult.sourceAsString()行中得到NullPointerException 似乎更新响应在更新操作后不包含文档。 是否可以从更新响应中返回文档_source

Elastic4s似乎在UpdateDefinition (目前为2015年7月23日 )中没有用于设置字段的api。 但是它的构建器支持此操作,下面的代码就像肮脏的hack,但是它可以作为exepcted使用,只需将字段直接设置为_builder

val updateRequest = update id re.getId in "my_index/user" doc StringDocumentSource(updateString) docAsUpsert true
updateRequest._builder.setFields("_source")
client.execute {
    updateRequest
    }.map { res=>
        println("Ololo result is: " + res.getGetResult.sourceAsString())
    }
}

版画

Ololo indexed id: AU66n1yiYVxOgU2h4AoG
Ololo result is: {"name":"jojn","surname":"123","global":{"new":"fiedl"}}
Ololo ok

注意

Elasticsearch 确实 支持在更新请求后返回字段。

更新

之后Elastic4s 通过承诺支持这一UpdateDsl.includeSourceUpdateDsl.setFields方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM