'REST'에 해당되는 글 4건

  1. 2018.06.27 [Elasticsearch] Move TransportClient to High Level REST Client
  2. 2017.02.01 [Appboy] REST API 를 이용한 이벤트 처리
  3. 2016.07.22 [Elasticsearch] Transport Bulk to Rest Bulk data format 변환
  4. 2015.07.02 [Elasticsearch] shard allocation 운영 테스트용 REST 코드

[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();
}




:

[Appboy] REST API 를 이용한 이벤트 처리

ITWeb/개발일반 2017. 2. 1. 14:01

앱보이 API 를 이용해서 앱에서 이벤트 푸쉬를 발생 하기 위한 예제 코드 입니다.

네이티브 앱은 SDK 를 이용하면 되지만 웹뷰는 REST API 를 이용해야 합니다.


# endpoint

https://api.appboy.com/users/track

 

# method

POST

 

# header

Content-Type: application/json

 

# body raw

{

"app_group_id":"xxxxx-xxxxx-xxxx-xxxxx",

"events": [

    {

        "external_id":"xxxxx-xxxxxx-xxxxxxx-xxxxxx",

        "name":"$EVENT_NAME$",

        "properties": {

            "keyword":"$KEYWORD$"

        },

        "time":"2017-01-26T07:10:00+09:00"

    }

]

}


참고문서)

https://www.appboy.com/documentation/REST_API/

:

[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"


:

[Elasticsearch] shard allocation 운영 테스트용 REST 코드

Elastic/Elasticsearch 2015. 7. 2. 18:18
매번 작성 하기 귀찮아서 그냥 남겨 봅니다.

[shard allocation disable]
curl -XPUT localhost:9200/_cluster/settings -d '{
    "persistent" : {
    "cluster.routing.allocation.disable_allocation" : true
    }
}'

[모든 종류의 shard allocation disable]
curl -XPUT localhost:9200/_cluster/settings -d '{
    "transient" : {
        "cluster.routing.allocation.enable" : "none"
    }
}'

[shard allocation enable]
curl -XPUT localhost:9200/_cluster/settings -d '{
    "persistent" : {
    "cluster.routing.allocation.disable_allocation" : false
    }
}'

[모든 종류의 shard allocation enable]
curl -XPUT localhost:9200/_cluster/settings -d '{
    "transient" : {
        "cluster.routing.allocation.enable" : "all"
    }
}'

[모든 인덱스의 replica shard disable]
curl -XPUT localhost:9200/*/_settings -d '{"number_of_replicas":0}'



: