본문 바로가기

IT/Elasticsearch

Elasticsearch Client Java 코드 메모

Elasticsearch Java Client를 통해 RestAPI에 접근하는 코드를 몇 줄 메모해둠.


Count API

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

import org.apache.log4j.Logger;
import org.elasticsearch.action.count.CountResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

import static org.elasticsearch.index.query.QueryBuilders.*;

public class CountExample {
	
	private static final Logger LOGGER = Logger.getLogger(CountExample.class);

	@SuppressWarnings("resource")
	public static void main(String[] args) {
		
		Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "클러스터명").build();
		Client client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress("IP주소", 9300));
		
		CountResponse countResp = client.prepareCount("인덱스명")
				.setTypes("타입명")
				.setQuery(multiMatchQuery("검색할 단어", new String[]{"필드명#1", "필드명#2"}))
				.execute().actionGet();
		
		LOGGER.info(countResp.getCount());
		
		client.close();
		
	}
	
}

Index API

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

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.elasticsearch.action.WriteConsistencyLevel;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

public class IndexExample {

	private static final Logger LOGGER = Logger.getLogger(CountExample.class);
	
	@SuppressWarnings("resource")
	public static void main(String[] args) throws IOException {
		
		Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "클러스터명").build();
		Client client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress("IP주소", 9300));
		
		IndexResponse indexResp = client.prepareIndex("인덱스명", "타입명")
				.setOperationThreaded(false)
				.setConsistencyLevel(WriteConsistencyLevel.QUORUM)
				.setRefresh(false)
				.setSource(jsonBuilder()
						.startObject()
						.field("필드명#1", "값#1")
						.field("필드명#2", "값#2")
						.endObject())
				.execute().actionGet();
		
		LOGGER.info(indexResp.isCreated());
		
		client.close();
		
	}
	
}

Search(Scroll) API

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

import org.apache.log4j.Logger;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.search.SearchHit;

public class SearchScrollExample {
	
	private static final Logger LOGGER = Logger.getLogger(SearchScrollExample.class);

	@SuppressWarnings("resource")
	public static void main(String[] args) {
		
		Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "modified").build();
		Client client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress("localhost", 9300));
		
		SearchResponse scrollResp = client.prepareSearch("articles")
				.setTypes("article")
				.setSearchType(SearchType.SCAN)
				.setScroll(new TimeValue(60000))
				.setSize(10)
				.execute().actionGet();
		
		while ( true ) {
			
			// 실제 약속한 size 만큼의 데이터를 가져와서 처리하는 부분
			for ( SearchHit hit : scrollResp.getHits().getHits() ) {
				LOGGER.info(hit.getSourceAsString());
			}
			
			// ScrollResponse 객체에서 scrollId를 추출, 이를 파라미터로 다음 ScrollBach에 해당하는 데이터를 재호출한다.
			scrollResp = client.prepareSearchScroll(scrollResp.getScrollId())
					.setScroll(new TimeValue(60000))
					.execute().actionGet();
			
			// 받아온 ScrollResponse 객체에 문서가 없을 경우 while문을 종료한다.
			if ( scrollResp.getHits().getHits().length == 0 ) { break; }
				
		}
		
		client.close();
		
	}
	
}