ESHelper.java 5.21 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
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;
张辰's avatar
张辰 committed
25
import org.springframework.beans.factory.annotation.Value;
张辰's avatar
张辰 committed
26 27 28 29 30 31 32 33 34 35 36 37 38
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 {

张辰's avatar
张辰 committed
39 40 41
    @Value("${es.index}")
    private String esIndex;

张辰's avatar
张辰 committed
42 43 44 45
    @Autowired
    private RestHighLevelClient client;


张辰's avatar
张辰 committed
46
    public void insert(String type, String id, String json) {
张辰's avatar
张辰 committed
47
        try {
张辰's avatar
张辰 committed
48
            IndexRequest req = new IndexRequest(esIndex);
张辰's avatar
张辰 committed
49 50 51 52 53 54
            if (StringUtils.isNotBlank(id)) {
                req.id(type + "_" + id);
            }

            req.source(json, XContentType.JSON);
            IndexResponse resp = client.index(req, RequestOptions.DEFAULT);
张辰's avatar
张辰 committed
55
            validStatus(resp.status(), RestStatus.CREATED, RestStatus.OK);
张辰's avatar
张辰 committed
56 57 58 59 60
        } catch (IOException e) {
            log.error("ES Helper error:{}", ExceptionUtils.getStackTrace(e));
        }
    }

张辰's avatar
张辰 committed
61
    public void insert(String type, String id, Map<String, Object> data) {
张辰's avatar
张辰 committed
62
        try {
张辰's avatar
张辰 committed
63
            IndexRequest req = new IndexRequest(esIndex);
张辰's avatar
张辰 committed
64 65 66 67 68 69
            if (StringUtils.isNotBlank(id)) {
                req.id(type + "_" + id);
            }

            req.source(data);
            IndexResponse resp = client.index(req, RequestOptions.DEFAULT);
张辰's avatar
张辰 committed
70
            validStatus(resp.status(), RestStatus.OK);
张辰's avatar
张辰 committed
71 72 73 74 75
        } catch (IOException e) {
            log.error("ES Helper error:{}", ExceptionUtils.getStackTrace(e));
        }
    }

张辰's avatar
张辰 committed
76
    public SearchHit[] selectLike(SearchSourceBuilder builder) {
张辰's avatar
张辰 committed
77
        try {
张辰's avatar
张辰 committed
78
            SearchRequest req = new SearchRequest(esIndex);
张辰's avatar
张辰 committed
79 80 81 82 83 84 85 86 87 88 89 90 91
            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[]{};
    }


张辰's avatar
张辰 committed
92 93 94
    private void validStatus(RestStatus status, RestStatus... expect) {
        for (RestStatus ex : expect) {
            if (ex == status) return;
张辰's avatar
张辰 committed
95
        }
张辰's avatar
张辰 committed
96 97
        log.error("ES Helper fail! status:{}", status.toString());
        throw new RuntimeException("ES fail");
张辰's avatar
张辰 committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    }


















    public static void main(String[] args) {
张辰's avatar
张辰 committed
118 119 120
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("1", "2"));

张辰's avatar
张辰 committed
121 122 123 124
        RestClientBuilder builder = RestClient.builder(new HttpHost("42.194.224.208", 9200))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
张辰's avatar
张辰 committed
125
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
张辰's avatar
张辰 committed
126 127 128 129 130 131 132 133 134 135 136 137
                    }
                });

        RestHighLevelClient highClient = new RestHighLevelClient(builder);

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


        System.out.println("insert");

        Map<String, Object> map = new HashMap<>();
张辰's avatar
张辰 committed
138 139 140
        map.put("name", "太阳44444444444444");
        map.put("context", "这里有一个小太阳444444444");
//        helper.insert("test_index", "", "2", map);
张辰's avatar
张辰 committed
141 142 143 144 145 146



        SearchSourceBuilder search = new SearchSourceBuilder();

        BoolQueryBuilder boolQb = QueryBuilders.boolQuery();
张辰's avatar
张辰 committed
147
        MatchQueryBuilder matchQb = QueryBuilders.matchQuery("textContent", "小星星");
张辰's avatar
张辰 committed
148 149
        boolQb.must(matchQb);

张辰's avatar
张辰 committed
150 151 152
//        String[] includes = new String[]{"id"};
//        String[] excludes = new String[]{};
        search.query(boolQb).from(0).size(50);
张辰's avatar
张辰 committed
153 154


张辰's avatar
张辰 committed
155
        SearchHit[] hits = helper.selectLike(search);
张辰's avatar
张辰 committed
156 157 158 159 160
        System.out.println(hits.length);
        for (SearchHit hit : hits) {
            System.out.println(hit.toString());
            System.out.println(hit.getFields());
        }
张辰's avatar
张辰 committed
161
        System.out.println("done");
张辰's avatar
张辰 committed
162 163 164 165
    }


}