2017-12-12 10 views
1

자바 하이 레벨 REST 클라이언트를 사용하고 있습니다. 여기에있다 link to its documentationelasticsearch에 중첩 된 필드를 저장하는 방법

나는 클라이언트를 만들었습니다.

trait HighLevelRestClient { 

    def elasticSearchClient(): RestHighLevelClient = { 
    new RestHighLevelClient(
     RestClient.builder(
     new HttpHost("localhost", ElasticSearchPort, "http"))) 
    } 
} 

데이터를 인덱싱하지만

는 중첩 필드 문자열로 저장되어있다. 다음 코드는 인덱스가 생성되는 방법을 설명합니다 :

val indexRequest = new IndexRequest("my-index", "test-type").source(
    "person", person, 
    "date", DateTime.now() 
) 

, 사람으로 표현되는 경우 클래스입니다 :

Person(personId: String, name: String, address: Address) 

및 주소로서 표현되는 경우 클래스 자체입니다 :

Address(city: String, zip: Int) 

내 응용 프로그램에서는 사람을 키 - 값 쌍으로 저장해야 필드를 검색 할 수 있습니다. 그러나 위의 코드를 사용하면 String으로 저장됩니다.

{ 
"person" : "Person(my-id, my-name, Address(my-city, zip-value))", 
"date" : "2017-12-12" 
} 

및 필요한 구조는 다음과 같습니다

{ 
"person" : { 
    "personId" : "my-id", 
    "name" : "person-name", 
    "address": { 
     "city" : "city-name", 
     "zip" : 12345 
      } 
    }, 
"date" : "2017-12-12" 
} 

내가 잘 질문 액자를 바랍니다. 어떤 도움을 주시면 감사하겠습니다. 감사!

답변

0

거의 다 왔었습니다. 당신의 목표를 달성하기 위해 다음을 수행해야합니다

  1. 직렬화 JSON으로 객체를 옆
  2. 에 그것은 실제로 Index API의 페이지에 설명되어있는 요청

의 내용 유형을 지정합니다.

사례 클래스를 JSON으로 직렬화하는 편리한 라이브러리는 예를 들어 json4s입니다 (일련 번호 here의 몇 가지 예를 볼 수 있습니다). 이 경우에 것을

import org.apache.http.HttpHost 
import org.elasticsearch.action.index.IndexRequest 
import org.elasticsearch.client.{RestClient, RestHighLevelClient} 
import org.elasticsearch.common.xcontent.XContentType 
import org.joda.time.DateTime 
import org.json4s.NoTypeHints 
import org.json4s.jackson.Serialization 
import org.json4s.jackson.Serialization.write 

case class Address(city: String, zip: Int) 

case class Person(personId: String, name: String, address: Address) 

case class Doc(person: Person, date: String) 

object HighClient { 
    def main(args: Array[String]): Unit = { 
    val client = new RestHighLevelClient(
     RestClient.builder(
     new HttpHost("localhost", 9206, "http"))) 

    implicit val formats = Serialization.formats(NoTypeHints) 

    val doc = Doc(
     Person("blah1", "Peter Parker", Address("New-York", 33755)), 
     DateTime.now().toString 
    ) 

    val indexRequest = new IndexRequest("my-index", "test-type").source(
     write(doc), XContentType.JSON 
    ) 

    client.index(indexRequest) 

    client.close() 
    } 
} 

참고 :

new IndexRequest("my-index", "test-type").source(
    write(doc), XContentType.JSON 
) 

이 기능이 사용됩니다

코드는 다음과 같이 보일 수 있습니다 public IndexRequest source(String source, XContentType xContentType)

귀하의 경우 일 때 :

new IndexRequest("my-index", "test-type").source(
    "person", person, 
    "date", DateTime.now() 
) 

전화는 public IndexRequest source(Object... source)입니다.

희망 하시겠습니까?