elasticsearch组合查询INDEX、TYPE等JAVA工具类封装分享(原创)

import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.JestResult;
import io.searchbox.client.config.HttpClientConfig;
import io.searchbox.cluster.Health;
import io.searchbox.cluster.NodesInfo;
import io.searchbox.cluster.NodesStats;
import io.searchbox.core.*;
import io.searchbox.indices.*;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.jws.soap.SOAPBinding;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class testEs {
    private static final Logger log = LoggerFactory.getLogger(testEs.class);
    private static JestClient client;
    private static final String CLUSTER_NAME = "myEs";
    private static  HttpClientConfig httpClientConfig;
    static {
        httpClientConfig = new HttpClientConfig.Builder("http://192.168.180.130:9200")
                .multiThreaded(true).connTimeout(Integer.MAX_VALUE).readTimeout(Integer.MAX_VALUE).defaultMaxTotalConnectionPerRoute(2)
                .gson(new GsonBuilder()
                        .setDateFormat("yyyy-MM-dd HH:mm:ss")
                        .create()).build();
        JestClientFactory factory = new JestClientFactory();
        factory.setHttpClientConfig(httpClientConfig);
        client = factory.getObject();
    }

    public static void main(String[] args) throws IOException {
       /* User user = new User();
        user.setEmpno("1");
        user.setNickName("afd");
        user.setUname("baba");
        JestResult jestResult = createIndex(user,"yangqing1","1","yangqing2");*/

        /*User user = new User();
        List<SearchResult.Hit<User, Void>> jestResult =  searchAll("yangqing1",user);
        for(SearchResult.Hit<User, Void> s : jestResult){
            user = s.source;
        }*/

        User user = new User();
        user.setUname("baba");
        List<SearchResult.Hit<User, Void>> jestResult =  createSearch("af","yangqing1",user);
        for(SearchResult.Hit<User, Void> s : jestResult){
            user = s.source;
        }

        System.out.println(user);
        //复核查询  有需要时网上搜索: mappering等等
    }

    /**
     * 创建索引并存入值
     * @param o 数据  index 索引名 id 主键  type数据库
     * @return  jestResult
     */
    public static <T> JestResult createIndex(T o, String index, String id, String type) {
        Index index1 = new Index.Builder(o).index(index).type(type).id(id).build();
        JestResult jestResult = null ;
        try {
            jestResult = client.execute(index1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jestResult;
    }

    /**
     * 删除索引
     * @param type :当前删除document名称
     * @return
     */
    public static JestResult deleteIndex(String type) {
        DeleteIndex deleteIndex = new DeleteIndex.Builder(type).build();
        JestResult result = null ;
        try {
            result = client.execute(deleteIndex);
            log.info("deleteIndex == " + result.getJsonString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result ;
    }

    /**
     * 判断索引是否存在
     * @param indexName
     * @return  jestResult
     */
    public static JestResult indicesExists(String indexName) {
        IndicesExists indicesExists = new IndicesExists.Builder(indexName).build();
        JestResult result = null ;
        try {
            result = client.execute(indicesExists);
            log.info("indicesExists == " + result.getJsonString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result ;
    }

    public static  <T> void bulkIndex(String index, String type , T o) {
        Bulk bulk = new Bulk.Builder()
                .defaultIndex(index)
                .defaultType(type)
                .addAction(Arrays.asList(
                        new Index.Builder(o).build()
                )).build();
        try {
            client.execute(bulk);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询全部
     * @param index :文档在哪存放
     * @return
     */
    public static  <T> List<SearchResult.Hit<T,Void>> searchAll(String index , T o){
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        Search search = new Search.Builder(searchSourceBuilder.toString())
                .addIndex(index)
                .build();
        SearchResult result = null ;
        List<?> hits = null ;
        try {
            result = client.execute(search);
            log.info("本次查询共查到:"+result+"个关键字!");
            hits = result.getHits(o.getClass());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return (List<SearchResult.Hit<T, Void>>) hits ;
    }

    /**
     * 搜索
     * @param keyWord :搜索关键字
     * @return
     */
    public static <T> List<SearchResult.Hit<T,Void>> createSearch(String keyWord , String type , T o , String... fields){
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(QueryBuilders.queryStringQuery(keyWord));
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            for(String field : fields){
                highlightBuilder.field(field);//高亮field
            }
            highlightBuilder.preTags("<em>").postTags("</em>");//高亮标签
            highlightBuilder.fragmentSize(200);//高亮内容长度
            searchSourceBuilder.highlighter(highlightBuilder);
            Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(type).build();
            SearchResult result = null ;
            List<?> hits = null ;
            try {
                result = client.execute(search);
                hits = result.getHits(o.getClass());

            } catch (IOException e) {
                e.printStackTrace();
            }
            return (List<SearchResult.Hit<T, Void>>) hits ;
        }

    /**
     * 获取Document
     * @param o :返回对象
     * @param index :文档在哪存放
     * @param type : 文档表示的对象类别
     * @param id :文档唯一标识
     * @return
     */
    public static  <T> JestResult getDocument(T o , String index , String type , String id){
        Get get = new Get.Builder(index, id).type(type).build();
        JestResult result = null ;
        try {
            result = client.execute(get);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 搜索事件流图表数据
     * @param param
     * @return
     */
    public static JsonObject searchEvent(String param){
        JsonObject returnData = new JsonParser().parse(param).getAsJsonObject();
        Search search = new Search.Builder(returnData.toString()).addType("event").addIndex("pi").build();

//      Gson gs = new Gson();
//      System.out.println("输入参数为:" + "\n" + gs.toJson(search));

        SearchResult result = null ;
        try {
            result = client.execute(search);
//          System.out.println("\n" + gs.toJson(result.getJsonObject()) + "\n" );
//          System.out.println("本次查询共查到:" + "\n" +result.getTotal()+"个结果!");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.getJsonObject();
    }

    public static JestResult clearCache() {
        ClearCache closeIndex = new ClearCache.Builder().build();
        JestResult result = null ;
        try {
            result = client.execute(closeIndex);
            log.info("clearCache == " + result.getJsonString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result ;
    }

    public static JestResult closeIndex(String type) {
        CloseIndex closeIndex = new CloseIndex.Builder(type).build();
        JestResult result = null ;
        try {
            result = client.execute(closeIndex);
            log.info("closeIndex == " + result.getJsonString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result ;
    }
    //优化索引
    public static JestResult optimizeIndex() {
        Optimize optimize = new Optimize.Builder().build();
        JestResult result = null ;
        try {
            result = client.execute(optimize);
            log.info("optimizeIndex == " + result.getJsonString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result ;
    }

    public static JestResult flushIndex() {
        Flush flush = new Flush.Builder().build();
        JestResult result = null ;
        try {
            result = client.execute(flush);
            log.info("flushIndex == " + result.getJsonString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result ;
    }

    public static JestResult nodesInfo() {
        NodesInfo nodesInfo = new NodesInfo.Builder().build();
        JestResult result = null ;
        try {
            result = client.execute(nodesInfo);
            log.info("nodesInfo == " + result.getJsonString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result ;
    }

    public static JestResult health() {
        Health health = new Health.Builder().build();
        JestResult result = null ;
        try {
            result = client.execute(health);
            log.info("health == " + result.getJsonString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result ;
    }

    public static JestResult nodesStats() {
        NodesStats nodesStats = new NodesStats.Builder().build();
        JestResult result = null ;
        try {
            result = client.execute(nodesStats);
            log.info("nodesStats == " + result.getJsonString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result ;
    }

    public static JestResult updateDocument(String script , String index, String type, String id) {
        /*String script = "{" +
                "    \"doc\" : {" +
                "        \"title\" : \""+article.getTitle()+"\"," +
                "        \"content\" : \""+article.getContent()+"\"," +
                "        \"author\" : \""+article.getAuthor()+"\"," +
                "        \"source\" : \""+article.getSource()+"\"," +
                "        \"url\" : \""+article.getUrl()+"\"," +
                "        \"pubdate\" : \""+new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(article.getPubdate())+"\"" +
                "    }" +
                "}";*/
        Update update = new Update.Builder(script).index(index).type(type).id(id).build();
        JestResult result = null ;
        try {
            result = client.execute(update);
            log.info("updateDocument == " + result.getJsonString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result ;
    }

    public static JestResult deleteDocument(String index, String type, String id) {
        Delete delete = new Delete.Builder(id).index(index).type(type).build();
        JestResult result = null ;
        try {
            result = client.execute(delete);
            log.info("deleteDocument == " + result.getJsonString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static JestResult deleteDocumentByQuery(String index, String type, String params) {

        DeleteByQuery db = new DeleteByQuery.Builder(params)
                .addIndex(index)
                .addType(type)
                .build();

        JestResult result = null ;
        try {
            result = client.execute(db);
            log.info("deleteDocument == " + result.getJsonString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值