ESHelper.java 4.83 KB
Newer Older
张辰's avatar
张辰 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
package com.tanpu.community.service.base;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.elasticsearch.client.*;

import javax.annotation.PostConstruct;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class ESHelper {

    @Autowired
    private RestHighLevelClient client;



    public void insert(String index, String type, String id, String json) {
        try {
            IndexRequest req = new IndexRequest(index);
            if (StringUtils.isNotBlank(id)) {
                req.id(type + "_" + id);
            }

            req.source(json, XContentType.JSON);
            IndexResponse resp = client.index(req, RequestOptions.DEFAULT);
            validStatus(resp.status(), RestStatus.CREATED);
        } catch (IOException e) {
            log.error("ES Helper error:{}", ExceptionUtils.getStackTrace(e));
        }
    }

    public void insert(String index, String type, String id, Map<String, Object> data) {
        try {
            IndexRequest req = new IndexRequest(index);
            if (StringUtils.isNotBlank(id)) {
                req.id(type + "_" + id);
            }

            req.source(data);
            IndexResponse resp = client.index(req, RequestOptions.DEFAULT);
            validStatus(resp.status(), RestStatus.CREATED);
        } catch (IOException e) {
            log.error("ES Helper error:{}", ExceptionUtils.getStackTrace(e));
        }
    }

    public SearchHit[] selectLike(String index, SearchSourceBuilder builder) {
        try {
            SearchRequest req = new SearchRequest(index);
            req.source(builder);
            SearchResponse resp = client.search(req, RequestOptions.DEFAULT);
            validStatus(resp.status(), RestStatus.OK);

            return resp.getHits().getHits();
        } catch (IOException e) {
            log.error("ES Helper error:{}", ExceptionUtils.getStackTrace(e));
        }

        return new SearchHit[]{};
    }


    private void validStatus(RestStatus status, RestStatus expect) {
        if (status != expect) {
            log.error("ES Helper fail! status:{}", status.toString());
            throw new RuntimeException("ES fail");
        }
    }


















    public static void main(String[] args) {
        RestClientBuilder builder = RestClient.builder(new HttpHost("42.194.224.208", 9200))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder;
                    }
                });

        RestHighLevelClient highClient = new RestHighLevelClient(builder);

        ESHelper helper = new ESHelper();
        helper.client = highClient;


        System.out.println("insert");

        Map<String, Object> map = new HashMap<>();
        map.put("name", "小行星2");
        map.put("context", "这里有一个小行星2");
//        helper.insert("test_index", "2", map);



        SearchSourceBuilder search = new SearchSourceBuilder();

        BoolQueryBuilder boolQb = QueryBuilders.boolQuery();
        MatchQueryBuilder matchQb = QueryBuilders.matchQuery("context", "星");
        boolQb.must(matchQb);

        String[] includes = new String[]{"id"};
        String[] excludes = new String[]{};
        search.query(boolQb).fetchSource(includes, excludes).from(0).size(50);


        SearchHit[] hits = helper.selectLike("test_index", search);
        System.out.println(hits.length);
        for (SearchHit hit : hits) {
            System.out.println(hit.toString());
            System.out.println(hit.getFields());
        }
    }


}