'transport'에 해당되는 글 5건

  1. 2020.09.10 [Elasticsearch+Docker] 로컬 클러스터 구성 시 흔한 실수.
  2. 2018.06.27 [Elasticsearch] Move TransportClient to High Level REST Client
  3. 2017.03.22 [Elasticsearch] Java API 5.2 - Maven Dependency Module
  4. 2017.03.09 [Elasticsearch] TransportClient on 5.x
  5. 2016.07.22 [Elasticsearch] Transport Bulk to Rest Bulk data format 변환

[Elasticsearch+Docker] 로컬 클러스터 구성 시 흔한 실수.

Elastic/Elasticsearch 2020. 9. 10. 08:54

Elasticsearch 가 각 노드들과 discovery 를 하기 위해서는 Transport 통신이 이루어져야 합니다.

문서에 정확하게 나와 있으나 놓치기 쉬운 부분이라 기록해 봅니다.

 

[참고문서]

https://www.elastic.co/guide/en/elasticsearch/reference/current/discovery-settings.html
https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-discovery-bootstrap-cluster.html
https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-discovery-settings.html

 

[Content Snippet]

[discovery.seed_hosts]

Provides a list of the addresses of the master-eligible nodes in the cluster.

1. transport.profiles.default.port
2. transport.port
If neither of these is set then the default port is 9300.

[Example Configuration]

[Node 1 - docker-compose.yml]
version: '3.7'

services:
  docker-es:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.9.1
    container_name: e1
    environment:
      - cluster.name=e3k1
      - node.name=e1
...중략...
      - discovery.seed_hosts=host.docker.internal:9300,host.docker.internal:9301,host.docker.internal:9302
      - cluster.initial_master_nodes=e1,e2,e3
...중략...

[Node 2 - docker-compose.yml]
version: '3.7'

services:
  docker-es:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.9.1
    container_name: e2
    environment:
      - cluster.name=e3k1
      - node.name=e2
...중략...
      - discovery.seed_hosts=host.docker.internal:9300,host.docker.internal:9301,host.docker.internal:9302
      - cluster.initial_master_nodes=e1,e2,e3
...중략...

[Node 3 - docker-compose.yml]
version: '3.7'

services:
  docker-es:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.9.1
    container_name: e3
    environment:
      - cluster.name=e3k1
      - node.name=e3
...중략...
      - discovery.seed_hosts=host.docker.internal:9300,host.docker.internal:9301,host.docker.internal:9302
      - cluster.initial_master_nodes=e1,e2,e3
...중략...

 

위에 작성된 설정 예제는 로컬에서 3개의 Elasticsearch 컨테이너를 실행 시켜서 클러스터링 시키는 예제 입니다.

이 방법 말고도 하나의 docker-compose.yml 에 구성을 하셔도 됩니다. (단, 설정이 조금 달라 집니다.)

 

주의 점은,

위에 언급된 내용처럼 Transport 통신을 한다는 것을 잊으면 안된다는 것입니다.

:

[Elasticsearch] Move TransportClient to High Level REST Client

Elastic/Elasticsearch 2018. 6. 27. 11:46

이번에 새로 Indexer 모듈을 만들다 보니 아래 문서의 내용을 확인하게 되었습니다.


Reference)

https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/client.html

https://github.com/elastic/elasticsearch/tree/master/client/rest/src/test/java/org/elasticsearch/client


원문발췌)

We plan on deprecating the TransportClient in Elasticsearch 7.0 and removing it completely in 8.0. Instead, you should be using the Java High Level REST Client, which executes HTTP requests rather than serialized Java requests. The migration guidedescribes all the steps needed to migrate.

The Java High Level REST Client currently has support for the more commonly used APIs, but there are a lot more that still need to be added. You can help us prioritise by telling us which missing APIs you need for your application by adding a comment to this issue: Java high-level REST client completeness.

Any missing APIs can always be implemented today by using the low level Java REST Client with JSON request and response bodies.


사실 저도 TransportClient 를 사용하면 version 때문에 고민을 하긴했었는데요.

이 참에 그냥 REST Client 로 넘어 가야 겠다고 생각해서 새로 작성 하였습니다.


기본적인 예제 코드는 아래 내용 참고 하시면 됩니다.


public static void main(String[] args) {
requestRestClient();
}

public static void requestRestClient() {
int numNodes = 5; //randomIntBetween(1, 5);
HttpHost[] hosts = new HttpHost[numNodes];
for (int i = 0; i < numNodes; i++) {
hosts[i] = new HttpHost("localhost", 9200);
}
RestClientBuilder builder = RestClient.builder(hosts);
RestClient restClient = builder.build();

builder.setMaxRetryTimeoutMillis(10000);

builder.setFailureListener(new RestClient.FailureListener() {
@Override
public void onFailure(HttpHost host) {
System.out.println("onFailure");
}
});

builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
@Override
public RequestConfig.Builder customizeRequestConfig(
RequestConfig.Builder requestConfigBuilder) {
return requestConfigBuilder.setSocketTimeout(10000);
}
});

Map<String, String> params = new HashMap<>();
params.put("preference", "_shards:0,1,2,3");

HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory consumerFactory =
new HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory(
30 * 1024 * 1024);
try {
Response response = restClient
.performRequest("GET", "/hello/_search", params, null, consumerFactory);

System.out.println(response.toString());

// Read Case 1
RequestLine requestLine = response.getRequestLine();
HttpHost host = response.getHost();
int statusCode = response.getStatusLine().getStatusCode();
Header[] headers = response.getHeaders();
String responseBody = EntityUtils.toString(response.getEntity());

System.out.println(requestLine);
System.out.println(host);
System.out.println(statusCode);
System.out.println(headers);
System.out.println(responseBody);

// Read Case 2 - old fashion
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));

String inputLine;
StringBuffer buffer = new StringBuffer();

while ((inputLine = reader.readLine()) != null) {
buffer.append(inputLine);
}

reader.close();

// System.out.println(buffer.toString());
} catch (IOException e) {
e.printStackTrace();
}

try {
restClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public static int randomIntBetween(int min, int max) {
return RandomNumbers.randomIntBetween(random(), min, max);
}

public static Random random() {
return RandomizedContext.current().getRandom();
}




:

[Elasticsearch] Java API 5.2 - Maven Dependency Module

Elastic/Elasticsearch 2017. 3. 22. 16:07

5.x 로 업그레이드 되면서 몇 가지 바뀐 것들이 존재 합니다.

그 중 maven dependency 설정을 수정해 줘야 하는 것들이 있어서 그냥 기록해 봅니다.


참고문서)

https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/_maven_repository.html


<dependency>

    <groupId>org.elasticsearch.client</groupId>

    <artifactId>transport</artifactId>

    <version>5.2.2</version>

</dependency>


<dependency>

    <groupId>org.apache.logging.log4j</groupId>

    <artifactId>log4j-api</artifactId>

    <version>2.7</version>

</dependency>

<dependency>

    <groupId>org.apache.logging.log4j</groupId>

    <artifactId>log4j-core</artifactId>

    <version>2.7</version>

</dependency>


java api 사용하시는 분들은 위 설정을 추가해 주시면 에러 없이 잘 동작 할겁니다.

log4j2 설정 파일도 없으시다면 추가를 해주셔야 합니다.

:

[Elasticsearch] TransportClient on 5.x

Elastic/Elasticsearch 2017. 3. 9. 11:51

elasticsearch 2.4 에서 사용하던 java api 중 TransportClinet 사용 방법이 바뀌어서 작성 합니다.

변경된 내용에 대해서는 elasticsearch 공식 홈페이지에 자세히 나와 있습니다.


[참고문서]

https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/_maven_repository.html

https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/transport-client.html


[코드 변경]


2.x)

settings = settingsBuilder()

  .put("cluster.name", cluster)

  .put("client.transport.sniff", true)

  .put("network.tcp.blocking", false)           // tcp non-blocking mode

  .put("client.transport.ping_timeout", "10s")

  .build();


5.x)

settings = builder()

  .put("cluster.name", cluster)

  .put("client.transport.sniff", true)

  .put("network.tcp.blocking", false)           // tcp non-blocking mode

  .put("client.transport.ping_timeout", "10s")

  .build();


2.x)

TransportClient client = TransportClient.builder().settings(settings).build();


5.x)

TransportClient client = new PreBuiltTransportClient(settings);


여기서 주의 하실 점은 참고문서에 있지만  transport 가 분리 되었기 때문에 별도로 dependency 구성을 해주셔야 합니다.


Maven Dependency 추가)

<dependency>

  <groupId>org.elasticsearch.client</groupId>

  <artifactId>transport</artifactId>

  <version>${elasticsearch.version}</version>

</dependency>


별 내용은 아니지만 혹시라도 삽질 하시는 분들이 계실 수 있어 작성해 봤습니다.

:

[Elasticsearch] Transport Bulk to Rest Bulk data format 변환

Elastic/Elasticsearch 2016. 7. 22. 10:02

java 로 bulk indexing 코드를 구현할 경우 색인 데이터 format을 그대로 rest bulk indexing 에서 사용을 할 수가 없습니다.

그래서 변환 하는 스크립트를 간단하게 작성해 봤습니다.


Reference)

https://www.elastic.co/guide/en/elasticsearch/reference/2.3/docs-bulk.html


Java Bulk Indexing Format)

{ "field1" : "value1" }


Rest Bulk Indexing Format)

{ "index" : { "_index" : "test", "_type" : "type1", "_id" : "1" } }

{ "field1" : "value1" }


보시면 아시겠지만 index/type/id 에 대한 meta 정보가 있느냐 없느냐의 차이 입니다.

당연하겠지만 java api 에서는 meta 정보를 set 하도록 되어 있습니다. 하지만 rest api 에서는 set 하는 과정이 없기 때문에 당연히 정보를 위와 같이 넣어 줘야 합니다.


변환 스크립트)

#!/bin/bash


while read line

do

  header="{ \"index\" : { \"_index\" : \"INDEX_NAME\", \"_type\" : \"TYPE_NAME\" } }"

  echo -e $header >> query_result.txt

  echo -e $line >> query_result.txt

done < $1


실행)

$ ./convertJavaToRestFormat.sh query_result.json


Rest Bulk Action)

$ curl -XPOST 'http://localhost:9200/INDEX_NAME/TYPE_NAME/_bulk' --data-binary "@query_result.txt"


: