All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.tvd12.ezydata.elasticsearch.handler.EzyEsIndexActionHandler Maven / Gradle / Ivy

The newest version!
package com.tvd12.ezydata.elasticsearch.handler;

import com.tvd12.ezydata.elasticsearch.action.EzyEsIndexAction;
import com.tvd12.ezyfox.entity.EzyObject;
import com.tvd12.ezyfox.identifier.EzyIdFetcher;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class EzyEsIndexActionHandler extends EzyEsAbstractActionHandler {

    @SuppressWarnings("unchecked")
    @Override
    public BulkResponse handle(EzyEsIndexAction action) throws Exception {
        List objects = action.getObjects();
        BulkRequest bulkRequest = new BulkRequest();
        for (Object object : objects) {
            Class objectType = object.getClass();
            EzyIdFetcher idFetcher = idFetchers.getIdFetcher(objectType);
            Set indexes = action.getIndexes();
            Set defaultIndexes = indexedDataClasses.getIndexes(objectType);
            indexes.addAll(defaultIndexes);

            Object objectId = idFetcher.getId(object);
            EzyObject wrapper = marshaller.marshal(object);
            Map source = wrapper.toMap();

            for (String index : indexes) {
                IndexRequest indexRequest = new IndexRequest(index)
                    .id(objectId.toString())
                    .source(source);
                bulkRequest.add(indexRequest);
            }
        }
        RequestOptions requestOptions = action.getRequestOptions();
        return clientProxy.bulk(bulkRequest, requestOptions);
    }
}