Scala,Elasticsearch新的RestHighLevelClient和BulkProcessor

时间:2018-02-02 18:01:32

标签: java scala elasticsearch-6

在我的Scala项目中,我尝试使用新的RestHighLevelClient更改旧的transportClient,以连接到Elasticsearch(6.1)。

但是我在尝试创建BulkProcessor时遇到问题,我不知道如何将此示例从Java转换为Scala

`BulkProcessor.Builder builder = BulkProcessor.builder(client::bulkAsync, listener);`

我的代码是:

val client=new RestHighLevelClient(
  RestClient.builder(
    new HttpHost("localhost", 9200, "http") ) )

val builder: BulkProcessor.Builder =BulkProcessor.builder(client, listener)

但是我得到了这个错误:

 overloaded method value builder with alternatives:
[error]   (x$1: java.util.function.BiConsumer[org.elasticsearch.action.bulk.BulkRequest,org.elasticsearch.action.ActionListener[org.elasticsearch.action.bulk.BulkResponse]],x$2: org.elasticsearch.action.bulk.BulkProcessor.Listener)org.elasticsearch.action.bulk.BulkProcessor.Builder <and>
[error]   (x$1: org.elasticsearch.client.Client,x$2: org.elasticsearch.action.bulk.BulkProcessor.Listener)org.elasticsearch.action.bulk.BulkProcessor.Builder
[error]  cannot be applied to (org.elasticsearch.client.RestHighLevelClient, org.elasticsearch.action.bulk.BulkProcessor.Listener)
[error]   val builder: BulkProcessor.Builder =BulkProcessor.builder(client, listener)

如果我尝试转换&#34; client::bulkAsync&#34;用&#34; client.bulkAsync _&#34;或&#34; client::bulkAsync(_._._)&#34;获取其他错误:

type mismatch;
[error] found   : org.apache.http.Header*
[error] required: org.apache.http.Header
[error] var bulkProcessor =BulkProcessor.builder(client.bulkAsync(_,_,_),listener)

这是Java中的方法bulkAsync:

 public final void bulkAsync(BulkRequest bulkRequest, ActionListener<BulkResponse> listener, Header... headers) {

有没有人在Scala中使用RestHighLevelClient和BulkProcessor?或知道如何修复此错误?

1 个答案:

答案 0 :(得分:2)

Scala 2.11与Java 8函数接口没有很好的互操作性。 创建BiConsumerId(接受两个输入参数并且不返回结果)应该可以解决此问题:

val bulkAsyncAsJava :  BiConsumer[BulkRequest, ActionListener[BulkResponse]] = new BiConsumer[BulkRequest, ActionListener[BulkResponse]] {
  override def accept(bulkRequest : BulkRequest , actionListener:ActionListener[BulkResponse]): Unit = {
    restHighLevelClient.bulkAsync(bulkRequest, actionListener)
  }
}
val bulkProcessor = BulkProcessor.builder(bulkAsyncAsJava, new BulkProcessor.Listener() {
override def beforeBulk(executionId: Long, request: BulkRequest): Unit = {
}

override

def afterBulk(executionId: Long, request: BulkRequest, response: BulkResponse): Unit = {
}

override

def afterBulk(executionId: Long, request: BulkRequest, failure: Throwable): Unit = {
}}).build