'JAVA API'에 해당되는 글 3건

  1. 2013.04.10 [elasticsearch] Java API : Delete
  2. 2013.04.08 [elasticsearch] Java API : Index
  3. 2013.04.05 [elasticsearch] Java API : Client

[elasticsearch] Java API : Delete

Elastic/Elasticsearch 2013. 4. 10. 10:04

본 문서는 개인적인 테스트와 elasticsearch.org 그리고 community 등을 참고해서 작성된 것이며,

정보 교환이 목적입니다.


잘못된 부분에 대해서는 지적 부탁 드립니다.

(예시 코드는 성능 및 보안 검증이 되지 않았습니다.)



[elasticsearch java api 리뷰]

원문 링크 : http://www.elasticsearch.org/guide/reference/java-api/delete/


- 이 API는 index 의 id(_id) 를 기반으로 json 형식의 문서를 삭제 할 수 있습니다.

- Delete API 는 Get API 와 사용법이 유사 하기 때문에 간단하게 정리 합니다.


아래는 원문에서 제공하는 두 가지 예제 코드 입니다.

.setOperationThreaded(false) 옵션에 대한 설명은 이전 글 참고 바랍니다.

http://jjeong.tistory.com/795


[기본]

DeleteResponse response = client.prepareDelete("twitter", "tweet", "1")

        .execute()

        .actionGet();

- index name : twitter

- index type : tweet

- doc id (_id) : 1


[Threading Model 설정]

DeleteResponse response = client.prepareDelete("twitter", "tweet", "1")

        .setOperationThreaded(false)

        .execute()

        .actionGet();

:

[elasticsearch] Java API : Index

Elastic/Elasticsearch 2013. 4. 8. 18:42

본 문서는 개인적인 테스트와 elasticsearch.org 그리고 community 등을 참고해서 작성된 것이며,

정보 교환이 목적입니다.


잘못된 부분에 대해서는 지적 부탁 드립니다.

(예시 코드는 성능 및 보안 검증이 되지 않았습니다.)



[elasticsearch java api 리뷰]

원문 링크 : http://www.elasticsearch.org/guide/reference/java-api/index_/


json document 를 생성하는 몇 가지 방법을 설명하고 있습니다.

There are different way of generating JSON document:


- Manually (aka do it yourself) using native byte[] or as a String

- Using Map that will be automatically converted to its JSON equivalent

- Using a third party library to serialize your beans such as Jackson

- Using built-in helpers XContentFactory.jsonBuilder()


위 방법들 중에서 제일 아래 elasticsearch helper 를 이용한 방법을 테스트해 봅니다.


우선 간단하게 index 와 index type 을 정의해 보도록 하겠습니다.

curl -XPUT 'http://localhost:9200/facebook' -d '{

    "settings" : { 

        "number_of_shards" : 5,

        "number_of_replicas" : 1  

    },  

    "mappings" : { 

        "post" : { 

            "properties" : { 

                "docid" : { "type" : "string", "store" : "yes", "index" : "not_analyzed" },

                "title" : { "type" : "string", "store" : "yes", "index" : "analyzed", "term_vector" : "yes", "analyzer" : "standard" }

            }   

        }   

    }   

}'


- index 는 facebook 으로 생성을 하고

- index type 은 post 라고 생성을 합니다.

- settings 와 mappings 에 대한 상세한 내용은 아래 링크 참고 하시기 바랍니다.

http://www.elasticsearch.org/guide/reference/api/admin-indices-create-index/

http://www.elasticsearch.org/guide/reference/index-modules/

http://www.elasticsearch.org/guide/reference/mapping/

http://www.elasticsearch.org/guide/reference/mapping/core-types/


index, index type 생성이 끝났으면 이제 색인을 해보도록 하겠습니다

// 생성할 문서가 아래와 같다고 가정

// curl -XPUT 'http://localhost:9200/facebook/post/1' -d '{ "docid" : "henry", "title" : "This is the elasticsearch hadoop test." }'

// curl -XPUT 'http://localhost:9200/facebook/post/2' -d '{ "docid" : "henry", "title" : "elasticsearch test." }'

// curl -XPUT 'http://localhost:9200/facebook/post/3' -d '{ "docid" : "howook", "title" : "hadoop test." }'

// curl -XPUT 'http://localhost:9200/facebook/post/4' -d '{ "docid" : "howook", "title" : "test." }'


    IndexRequestBuilder requestBuilder;

    IndexResponse response;

        

    requestBuilder = client.prepareIndex("facebook", "post");

        

// setSource parameter 로 json string 형태로 등록

    requestBuilder.setId("1");

    requestBuilder.setSource("{ \"docid\" : \"henry\", \"title\" : \"This is the elasticsearch hadoop test.\" }");

    response = requestBuilder.execute().actionGet();


// XContentBuilder 로 setSource 전달

    XContentBuilder jsonBuilderDocument = jsonBuilder().startObject();

        jsonBuilderDocument.field("docid", "henry");

        jsonBuilderDocument.field("title", "elasticsearch test.");

    jsonBuilderDocument.endObject();

        

    requestBuilder.setId("2");

    requestBuilder.setSource(jsonBuilderDocument);

    response = requestBuilder.execute().actionGet();


- IndexRequestBuilder 의 setSource 에 대한 코드를 보시면 어떤 arguments 받는지 알 수 있습니다.

- 그리고 문서 색인에 사용되는 여러가지 다양항 옵션들은 아래 링크를 참고 하시기 바랍니다.

http://www.elasticsearch.org/guide/reference/api/index_/


아래는 index 생성 시 필요한 settings 와 mappings 에 대한 예제 코드 입니다.

맛보기 참고용 입니다.

IndicesAdminClient indices = client.admin().indices();

CreateIndexRequest indexRequest = new CreateIndexRequest("INDEX_NAME");

    indexRequest

        .settings(jsonBuilderIndexSetting)

        .mapping("INDEX_TYPE_NAME", jsonBuilderIndiceSetting);

indices.create(indexRequest).actionGet();

- INDEX_NAME 은 생성한 index

- INDEX_TYPE_NAME 은 생성한 index type

- jsonBuilerIndexSetting 과 jsonBuilderIndiceSetting 은 XContentBuilder 객체

:

[elasticsearch] Java API : Client

Elastic/Elasticsearch 2013. 4. 5. 19:01

본 문서는 개인적인 테스트와 elasticsearch.org 그리고 community 등을 참고해서 작성된 것이며,

정보 교환이 목적입니다.


잘못된 부분에 대해서는 지적 부탁 드립니다.

(예시 코드는 성능 및 보안 검증이 되지 않았습니다.)



[elasticsearch java api 리뷰]

원문 링크 : http://www.elasticsearch.org/guide/reference/java-api/client/


Java API 를 이용해서 elasticsearch 로 연결하는 두 가지 방법을 설명 하고 있습니다.

1. Node Client

2. Transport Client


※ 커뮤니티에서 관련 글들을 찾다 보면 kimchy 가 추천 하는 방식은 "TransportClient" 를 이용하는 것입니다.


원문에서 보면 elasticsearch 를 사용하면 주의 해야 하는 부분이 나와 있습니다.

사용하시면서 꼭 숙지 하시면 한번 쯤 실수 할 수 있는 오류를 범하지 않을 수 있습니다.

Important:

Please note that you are encouraged to use the same version on client and cluster sides. You may hit some incompatibilities issues when mixing major versions.



※ 요점은 버전을 혼합해서 사용하지 말라는 것입니다. (No Node Available Exception 의 이유가 됩니다.)


원문에 예제 코드가 잘 나와 있기 때문에 제가 테스트 한 코드를 아래 공유 합니다.

ClientConfig clientConfig = ClientConfig.getInstance();


// cluster.name 을 안 줄 경우 NoNodeAvailable 에러 발생.

settings = ImmutableSettings

        .settingsBuilder()

        .put("cluster.name", clientConfig.getProperty("cluster.name"))

        .build();

client = new TransportClient(settings)

        .addTransportAddress(new InetSocketTransportAddress(clientConfig.getProperty("cluster.host1")

                , Integer.parseInt(clientConfig.getProperty("cluster.host1.port"))))

        .addTransportAddress(new InetSocketTransportAddress(clientConfig.getProperty("cluster.host2")

                , Integer.parseInt(clientConfig.getProperty("cluster.host2.port"))));


- ClientConfig : elasticsearch 를 사용하기 위해 필요한 환경설정 값을 구성


elasticsearch client 가 가지는 properties 와 attributes 테스트를 위한 코드

@Test

public void testClientProperties() throws Exception {

    clientManager.openClient();

    Client client = clientManager.getClient();

    AdminClient admin = client.admin();

    ClusterAdminClient cluster = admin.cluster();

    IndicesAdminClient indices = admin.indices();


    ClusterStateRequestBuilder request = cluster.prepareState();

    ClusterStateResponse response = request.execute().actionGet();  

    ClusterState state = response.state();

    AllocationExplanation allocation = state.allocationExplanation();

    ClusterBlocks block = state.blocks();

    MetaData meta = state.metaData();

    RoutingNodes routingNode = state.routingNodes();

    RoutingTable routingTable = state.routingTable();

    ImmutableSettings settings = (ImmutableSettings) meta.persistentSettings();

    

    log.debug("{}", response.clusterName()); // Cluster [test.gruter.es.cluster]

    log.debug("{}", response.getClusterName());

    log.debug("{}", response.getHeaders());

    log.debug("{}", response.getState());

    log.debug("{}", response.state());

    

    log.debug("{}", state.allocationExplanation());

    log.debug("{}", state.blocks());

    log.debug("{}", state.metaData());

    log.debug("{}", state.nodes()); // {[test.gruter.es.cluster2.node][sIj29f-KQziaIbccn_jndg][inet[/127.0.0.1:9301]]{master=true},[test.gruter.es.cluster1.node][kWNDF8SLTxS_axatGmImIg][inet[/127.0.0.1:9300]]{master=true},}

    log.debug("{}", state.routingNodes());

    log.debug("{}", state.routingTable());

    log.debug("{}", state.version());

    

    log.debug("{}", allocation.explanations());

    

    log.debug("{}", block.indices());

    

    log.debug("{}", meta.concreteAllIndices());

    log.debug("{}", meta.concreteAllOpenIndices());

    log.debug("{}", meta.getTotalNumberOfShards());

    log.debug("{}", meta.persistentSettings());

    log.debug("{}", meta.settings());

    

    log.debug("{}", routingNode.getMetaData());

    log.debug("{}", routingNode.getNodesToShards());

    log.debug("{}", routingNode.getRoutingTable());

    log.debug("{}", routingNode.getUnassigned());

    log.debug("{}", routingNode.prettyPrint());

    

    log.debug("{}", routingTable.getIndicesRouting());

    log.debug("{}", routingTable.prettyPrint());

    

    log.debug("{}", settings.getAsMap());

    log.debug("{}", state.nodes().dataNodes());

    log.debug("{}", state.nodes().getSize());

   

    for ( int i=0; i<state.nodes().getSize(); i++ ) {

        log.debug("{}", state.nodes().dataNodes().keySet().toArray()[i]);

    }

    

    Set entries = state.nodes().dataNodes().entrySet();

    Iterator entryIter = entries.iterator();


    while (entryIter.hasNext()) {

        Map.Entry entry = (Map.Entry)entryIter.next();

        Object key = entry.getKey();

        Object value = entry.getValue();

       

        log.debug("key : {}", key);

        log.debug("value : {}", value);

    }

} 

※ 단순히 테스트 및 각 속성들을 보기 위한 코드 입니다.

: