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

时间:2015-07-23 05:16:06

标签: scala elasticsearch elastic4s

我正在尝试更新多个文档字段并在更新后返回完整文档。 我使用elasticsearch 1.3.4,{{3}} 1.4.3(作为服务器)。

这是一段代码:

    $data = array();

    $count = count($this->input->post['description']);

    for($i=0; $i < $count; $i++) {
        $data[] = array(
            'no'=>$this->input->post('num'),
            'descriptions' => $this->input->post['descriptions'][$i],
            'voucher' => $this->input->post['voucher'][$i],
            'des_price' => $this->input->post['des_price'][$i],
           );
    }
    $this->db->insert_batch('tbl_description', $data);

为什么我在行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") } 中获得NullPointerException?似乎更新响应在更新操作之后不包含文档。 是否可以从更新回复中返回文档res.getGetResult.sourceAsString()

1 个答案:

答案 0 :(得分:0)

Elastic4s似乎在UpdateDefinition(现在为23.07.2015)中没有api来设置字段。但是它的构建器支持这个操作,下面的代码就像脏黑客,但是它可以像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 support在更新请求后返回字段。

<强>更新

this提交后的Elastic4s通过UpdateDsl.includeSourceUpdateDsl.setFields方法支持此功能。