elasticsearch 집합 함수로distinct 조회 실현

자세히 보기
1. 등가의 sql
SELECT DISTINCT field1,field2 FROM test_index.test_type
등가
SELECT field1,field2 FROM test_index.test_type GROUP BY field1,field2

 
2. Group by 쿼리는 es에서 Aggregation (집합) 으로 구현할 수 있습니다. 등가의 DSL 쿼리 문장은 다음과 같습니다.
POST /test_index/test_type/_search
{
	"from": 0,
	"size": 0,
	"aggregations": {
		"field1": {
			"terms": {
				"field": "field1",
				"size": 2147483647
			},
			"aggregations": {
				"field2": {
					"terms": {
						"field": "field2",
						"size": 2147483647
					}
				}
			}
		}
	}
}
 
3.java의 실현:
import com.google.common.collect.ArrayListMultimap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Stack;
import java.util.stream.Collectors;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder;

/**
 *
 * @author zhongchenghui
 */
public class EsSearch {

    private static final String CLUSTER_NAME = "test_cluster";
    private static final String ES_ADDRESSES = "192.168.12.1,192.168.12.2,192.168.12.3";
    private static final String INDEX_NAME = "test_index";
    private static final Client ES_CLIENT = ESClientFactory.newInstance(CLUSTER_NAME, ES_ADDRESSES);

    /**
     *  group by 
     *
     * @param type
     * @param groupColumnsNames
     * @return
     * @throws Exception
     */
    public List> getRowsByGroup(String type, String... groupColumnsNames) throws Exception {
        TermsBuilder allTermsBuilder = createTermsAggregationBuilder(groupColumnsNames);
        SearchResponse response = createSearchRequestBuilder(type, groupColumnsNames).setSize(0).addAggregation(allTermsBuilder).execute().actionGet();
        List> rows = new ArrayList<>();
        Terms agg = response.getAggregations().get(groupColumnsNames[0]);
        int i = 0;
        agg.getBuckets().stream().forEach((bucket) -> {
            rows.addAll(getFlatBucket(i, bucket, groupColumnsNames));
        });
        return rows;
    }

    /**
     *  AggregationBuilder
     * ( Integer.MAX_VALUE )
     * @param groupColumnsNames
     * @return
     * @throws Exception
     */
    private TermsBuilder createTermsAggregationBuilder(String... groupColumnsNames) {
        TermsBuilder allTermsBuilder = AggregationBuilders.terms(groupColumnsNames[0]).field(groupColumnsNames[0]).size(Integer.MAX_VALUE);
        TermsBuilder tmpTermsBuilder = allTermsBuilder;
        for (int i = 1; i < groupColumnsNames.length; i++) {
            TermsBuilder termsBuilder = AggregationBuilders.terms(groupColumnsNames[i]).field(groupColumnsNames[i]).size(Integer.MAX_VALUE);
            tmpTermsBuilder.subAggregation(termsBuilder);
            tmpTermsBuilder = termsBuilder;
        }
        return allTermsBuilder;
    }

    /**
     *  Builder
     *
     * @param type
     * @param groupColumnsNames
     * @return
     * @throws Exception
     */
    private SearchRequestBuilder createSearchRequestBuilder(String type, String... columnNames) {
        SearchRequestBuilder searchRequestBuilder = ES_CLIENT.prepareSearch(INDEX_NAME).setTypes(type).setSize(50000);
        if (Objects.nonNull(columnNames) && columnNames.length > 0) {
            searchRequestBuilder.addFields(columnNames);
        }
        return searchRequestBuilder;
    }

    /**
     *  respone ( )
     *
     * @param layer
     * @param bucket
     * @param groupColumnsNames
     * @return
     */
    private List> getFlatBucket(int layer, Terms.Bucket bucket, String... groupColumnsNames) {
        ArrayListMultimap bucketRowMultimap = ArrayListMultimap.create();
        Stack nodeStack = new Stack<>();
        BucketNode bucketNode = new BucketNode(layer, groupColumnsNames[layer], bucket);
        nodeStack.add(bucketNode);
        bucketRowMultimap.put(bucketNode, bucketNode);
        while (!nodeStack.isEmpty()) {
            bucketNode = nodeStack.pop();
            List childerNodes = getChildrenBucketNodes(bucketNode, groupColumnsNames);
            if (childerNodes != null && !childerNodes.isEmpty()) {
                List parentRoute = bucketRowMultimap.removeAll(bucketNode);
                for (BucketNode child : childerNodes) {
                    nodeStack.push(child);
                    bucketRowMultimap.putAll(child, parentRoute);
                    bucketRowMultimap.put(child, child);
                }
            }
        }
        return convertToRows(bucketRowMultimap.asMap().values());
    }

    /**
     *  Bucket 
     *
     * @param parentNode
     * @param groupColumnsNames
     * @return
     */
    private List getChildrenBucketNodes(BucketNode parentNode, String... groupColumnsNames) {
        int currentLayer = parentNode.layer + 1;
        if (currentLayer < groupColumnsNames.length) {
            String currentAggName = groupColumnsNames[currentLayer];
            Terms currentAgg = parentNode.bucket.getAggregations().get(currentAggName);
            if (Objects.nonNull(currentAgg)) {
                return currentAgg.getBuckets().stream().map(bucket -> new BucketNode(currentLayer, currentAggName, bucket)).collect(Collectors.toList());
            }
        }
        return null;

    }

    private List> convertToRows(Collection> bucketRoutes) {
        return bucketRoutes.stream().map(bucketRoute -> convertToRow(bucketRoute)).collect(Collectors.toList());
    }

    private Map convertToRow(Collection bucketRoute) {
        Map row = new HashMap<>();
        bucketRoute.stream().forEach(bucketNode -> row.put(bucketNode.aggName, bucketNode.bucket.getKeyAsString()));
        return row;
    }

    class BucketNode {

        int layer;
        String aggName;
        Terms.Bucket bucket;

        public BucketNode(int layer, String aggName, Terms.Bucket bucket) {
            BucketNode.this.layer = layer;
            BucketNode.this.aggName = aggName;
            BucketNode.this.bucket = bucket;
        }

        @Override
        public String toString() {
            return "BucketNode{" + "layer=" + layer + ", aggName=" + aggName + ", bucket_key=" + bucket.getKeyAsString() + '}';
        }

    }
}

 
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author zhongchenghui
 */
public class ESClientFactory {

    private static final Logger LOGGER = LoggerFactory.getLogger(ESClientFactory.class);
    private static final ConcurrentHashMap CLIENT_CACHE = new ConcurrentHashMap<>();

    public static Client newInstance(String clusterName, String hostStr) {
        Client client = CLIENT_CACHE.get(clusterName);
        if (client == null) {
            Map addressMap = ESClientFactory.getESAddressMap(hostStr);
            Settings settings = Settings.settingsBuilder().put("cluster.name", clusterName).build();
            TransportClient newClient = TransportClient.builder().settings(settings).build();
            addressMap.keySet().forEach((host) -> {
                try {
                    newClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), addressMap.get(host)));
                } catch (UnknownHostException ex) {
                    LOGGER.error("Init ES client failure,cluster name is:{},Error:{}", clusterName, ex);
                }
            });
            client = newClient;
            CLIENT_CACHE.put(clusterName, newClient);
        }
        return client;
    }

    private static Map getESAddressMap(String hostStr) {
        Map hostMap = new HashMap<>();
        String[] hosts = hostStr.split(",");
        for (String host : hosts) {
            String[] hostPort = host.trim().split(":");
            Integer port = hostPort.length < 2 ? 9300 : Integer.valueOf(hostPort[1]);
            hostMap.put(hostPort[0], port);
        }
        return hostMap;
    }
}

 4.문제점:
a. 구현된 방식은 층층이 아래로 집합되기 때문에es의document에field1의 필드가null일 때 이 조건은 아래로 집합되지 않습니다. 설령 이document의field2 필드가 값이 있더라도.(null 대신 지정한 문자를 사용해서 이 문제를 해결할 수 있습니다)
b. 데이터 양이 너무 많은 테이블에 적합하지 않습니다. 3의 코드는 최대 각 필드의 그룹 수가 Integer보다 크면 안 됩니다.MAX_VALUE
c. 되돌아오는 필드는 그룹by에 참여하는 필드만 가능합니다.

좋은 웹페이지 즐겨찾기