elasticsearch (一)

springboot整合elasticsearch

使用原生Elasticsearch客户端API

  1. 组件版本
    springboot 2.1.3.RELEASE
    elasticsearch 5.4.3
  2. 使用springboot管理es
    (1)、maven

    org.elasticsearch
    elasticsearch
    5.4.3


    org.elasticsearch.client
    elasticsearch
    5.4.3


    org.elasticsearch.plugin
    transport-netty4-client
    5.4.3

(2)、配置信息

es:
  clusterName: elasticsearch
  port: 9309
  servers: xx.xx.xx.xx
@Component
@ConfigurationProperties(prefix = "es", ignoreInvalidFields = false)
public class EsConfig {

    @Value("${es.clusterName}")
    private String clusterName;
    @Value("${es.servers}")
    private String servers;
    @Value("${es.port}")
    private int port;

    public String getClusterName() {
        return clusterName;
    }

    public void setClusterName(String clusterName) {
        this.clusterName = clusterName;
    }

    public String getServers() {
        return servers;
    }

    public void setServers(String servers) {
        this.servers = servers;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}

(3)、注入配置、创建实例

@Repository
public class ElasticSearchRepository {
    private TransportClient client;

    @Autowired
    public ElasticSearchRepository(EsConfig esConfig) throws Exception {
        createInstance(esConfig);
    }
    protected void createInstance(EsConfig esConfig) throws Exception {
        Settings settings = Settings.builder()
                .put("cluster.name", esConfig.getClusterName())
                .build();
      
        client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(esConfig.getServers()), esConfig.getPort()));
    }

  1. 常用api
    /**
     * 创建一个索引
     *
     * @param indexName 索引名
     */
    public void createIndex(String indexName) {
        CreateIndexResponse indexResponse = this.client.admin().indices().prepareCreate(indexName).get();

    }


    /**
     * 给索引增加mapping。
     *
     * @param index 索引名
     * @param type  mapping所对应的type
     */
    public void addMapping(String index, String type, String typeJson) {
        client.admin().indices().preparePutMapping(index)
                .setType(type).setSource(typeJson, XContentType.JSON).execute().actionGet();

    }


    /**
     * 删除索引
     *
     * @param index 要删除的索引名
     */
    public void deleteIndex(String index) {
        DeleteIndexResponse deleteIndexResponse = this.client.admin().indices().prepareDelete(index).get();
    }



    /**
     * 创建一个文档
     *
     * @param index index
     * @param type  type
     */
    public void insertDoc(String index, String type, String data) {
        IndexRequest indexRequest = new IndexRequest(index, type);
        indexRequest.source(data, XContentType.JSON);
        IndexResponse indexResponse = client.index(indexRequest).actionGet();
    }


    public void batchInsertDoc(String index, String type, List dataList) {
        BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();

        for (String s : dataList) {
            IndexRequest request = client.prepareIndex(index, type).setSource(s, XContentType.JSON).request();
            bulkRequestBuilder.add(request);

        }
        bulkRequestBuilder.execute().actionGet();
    }


    /**
     * 更新文档
     *
     * @param index
     * @param type
     * @param id
     */
    public void updateDoc(String index, String type, String id, String jsonData) {
        UpdateResponse updateResponse = this.client.prepareUpdate().setIndex(index).setType(type).setId(id)
                .setDoc(jsonData, XContentType.JSON).get();
    }


    /**
     * 删除一条数据
     *
     * @param index
     * @param type
     * @param id
     */
    public void deleteDoc(String index, String type, String id) {
        DeleteResponse deleteResponse = this.client.prepareDelete().setIndex(index).setType(type).setId(id).get();
    }


    /**
     * 根据ID查询一条数据记录。
     *
     * @param id 要查询数据的ID。
     * @return 返回查询出来的记录对象的json字符串。
     */
    public Map get(String index, String type, String id) {
        GetResponse getResponse = this.client.prepareGet() // 准备进行get操作,此时还有真正地执行get操作。(与直接get的区别)
                .setIndex(index) // 要查询的
                .setType(type).setId(id).get();
        getResponse.getSource();
        return getResponse.getSource();
    }


    /**
     * 使用min聚合查询某个字段上最小的值。
     *
     * @param index
     * @param type
     */
    public void min(String index, String type) {
        SearchResponse response = this.client.prepareSearch(index)
                .addAggregation(AggregationBuilders.min("min").field("age")).get();
        InternalMin min = response.getAggregations().get("min");
    }


    public JSONObject search(String index, String type, SearchSourceBuilder ssb) {
        return search(index, type, ssb, true);
    }

    public JSONObject search(String index, String type, SearchSourceBuilder ssb, boolean includeId) {
        SearchResponse searchResponse = client.prepareSearch(index).setTypes(type).setSource(ssb).get();
        return extractFuzzyQueryResult(searchResponse, includeId);
    }


    protected JSONObject extractFuzzyQueryResult(SearchResponse searchResponse, boolean includeId) {
        SearchHits hits = searchResponse.getHits();
        long totalHits = hits.getTotalHits();
        List results = new ArrayList();
        for (SearchHit hit : searchResponse.getHits()) {
            JSONObject jo = JSONObject.parseObject(hit.getSourceAsString(), JSONObject.class);
            if (includeId) {
                jo.put("id", hit.getId());
            }
            results.add(jo);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", results);
        jsonObject.put("total", totalHits);
        return jsonObject;
    }

    protected JSONObject extractFuzzyQueryResult(MultiGetResponse multiGetItemResponses, boolean includeId) {
        long totalHits = multiGetItemResponses.getResponses().length;
        List results = new ArrayList();
        for (MultiGetItemResponse resp : multiGetItemResponses.getResponses()) {
            JSONObject jo = JSONObject.parseObject(resp.getResponse().getSourceAsString(), JSONObject.class);
            if(includeId){
                jo.put("id", resp.getId());
            }
            results.add(jo);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", results);
        jsonObject.put("total", totalHits);
        return jsonObject;
    }


    public void batchDeleteDoc(String index, String type, List ids) {
        BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
        for (String id : ids) {
            bulkRequestBuilder.add(client.prepareDelete(index, type, id));
        }
        bulkRequestBuilder.get();
    }

    public long count(String indexName, String typeName, SearchSourceBuilder ssb) {
        return client.prepareSearch(indexName).setTypes(typeName).setSource(ssb).setSize(0).get().getHits().getTotalHits();
    }


    public long count(String indexName, String typeName) {
        return client.prepareSearch(indexName).setTypes(typeName).setSize(0).get().getHits().getTotalHits();
    }


    public boolean checkIndex(String index) {
        return client.admin().indices().exists(new IndicesExistsRequest(index)).actionGet().isExists();
    }

    public JSONObject findByIds(String index, String type, List ids) {
        return findByIds(index, type, ids, true);
    }

    public JSONObject findByIds(String index, String type, List ids, boolean includeId) {
        MultiGetRequestBuilder multiGetRequestBuilder = client.prepareMultiGet();
        multiGetRequestBuilder.add(index, type, ids);
        MultiGetResponse multiGetItemResponses = multiGetRequestBuilder.get();
        return extractFuzzyQueryResult(multiGetItemResponses, includeId);
    }

    public void updateSetting(String index, Map settings){
        UpdateSettingsRequest updateSettingsRequest = Requests.updateSettingsRequest(index).settings(settings);
        client.admin().indices().updateSettings(updateSettingsRequest).actionGet();
    }

    
    public void closeIndex(String index) {
        client.admin().indices().close(new CloseIndexRequest(index)).actionGet();
    }

    public void openIndex(String index) {
        client.admin().indices().open(new OpenIndexRequest(index)).actionGet();
    }

    public Map findById(String index, String type, String id) {
        Map sourceAsMap = this.client.prepareGet()
                .setIndex(index)
                .setType(type).setId(id).get().getSourceAsMap();
        sourceAsMap.put("id", id);
        return sourceAsMap;
    }
}

你可能感兴趣的:(elasticsearch (一))