无法访问类TransportClient中的构造函数TransportClient

时间:2016-07-12 11:09:58

标签: scala elasticsearch

我在ElasticSearch中编写了以下用于索引文档的类:

import java.net.InetAddress
import com.typesafe.config.ConfigFactory
import org.elasticsearch.client.transport.TransportClient
import org.elasticsearch.common.settings.Settings
import org.elasticsearch.common.transport.InetSocketTransportAddress
import play.api.libs.json.{JsString, JsValue}

/**
  * Created by liana on 12/07/16.
  */
class ElasticSearchConnector {

  private var transportClient: TransportClient = null
  private val host = "localhost"
  private val port = 9300
  private val cluster = "elasticsearch"
  private val indexName = "tests"
  private val docType = "test"

  def configElasticSearch(): Unit =
  {
    val settings = Settings.settingsBuilder().put("cluster.name", cluster).build()
    transportClient = new TransportClient(settings)
    transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port.toInt))
  }

  def putText(json: String, id: Int): String =
  {
    val response = transportClient.prepareIndex(indexName, docType, id)
                                  .setSource(json)
                                  .get()
    val responseId = response.getId
    responseId
  }
}

然后我按如下方式使用它:

val json = """val jsonString =
{
"title": "Elastic",
"price": 2000,
"author":{
"first": "Zachary",
"last": "Tong";
}
}"""

val ec = new ElasticSearchConnector()
ec.configElasticSearch()
val id = ec.putText(json)
System.out.println(id)

这是我收到的错误消息:

  

错误:(28,23)类TransportClient中的构造函数TransportClient   无法在类ElasticSearchConnector中访问       transportClient = new TransportClient(设置)

这里有什么问题?

1 个答案:

答案 0 :(得分:0)

在Elasticsearch Connector API中,TransportClient类没有公共构造函数,但有一个声明的私有构造函数。因此,您无法直接“新建”TransportClient的实例。 API使用Builder Pattern非常重要,以便创建TransportClient的实例,您需要执行以下操作:

val settings = Settings.settingsBuilder().put("cluster.name", cluster).build()
val transportClient = TransportClient.builder().settings(settings).build()
transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port.toInt))