简介

ES(Elasticsearch)是一个基于Lucene的分布式搜索引擎,它能够快速地存储、搜索和分析海量数据。它基于Apache Lucene搜索引擎库构建,提供了一个分布式的多用户全文搜索引擎,具有高度的扩展性和高可用性,可用于各种不同的应用程序,包括电子商务、日志分析、数据挖掘等领域。其由Elastic公司开发。它能够快速地存储、搜索和分析海量数据,是一种非常流行的开源搜索引擎。

ES可以用于各种不同的应用程序,包括全文搜索、日志分析、数据挖掘、业务指标分析等。以下是ES的一些典型应用场景:

  1. 搜索引擎:ES可以用于构建全文搜索引擎,支持复杂的查询和过滤操作,能够快速地检索海量数据。
  2. 日志分析:ES可以用于日志分析,支持实时的日志收集和分析,可以快速地找到日志中的异常和错误。
  3. 数据挖掘:ES可以用于数据挖掘,支持聚合操作和数据分析,可以从海量数据中提取有价值的信息。
  4. 业务指标分析:ES可以用于业务指标分析,支持实时的数据可视化和分析,可以帮助企业更好地了解业务运营情况。

ES的优点:

  1. 可扩展性:ES是一个分布式的搜索引擎,可以通过添加节点来扩展其容量和性能。
  2. 实时性:ES支持实时的数据索引和搜索,可以快速地响应查询请求。
  3. 多样化的查询方式:ES支持各种类型的查询方式,包括全文搜索、精确匹配、过滤等。
  4. 高可用性:ES支持数据的备份和复制,可以保证数据的高可用性和可靠性。
  5. 易于使用:ES提供了RESTful API和Java API,可以方便地进行数据的索引和查询操作。
  6. 社区活跃:ES是一个开源项目,拥有庞大的社区支持和贡献,可以快速地获取帮助和支持。 综上所述,ES是一个流行的分布式搜索引擎,具有高度的扩展性和高可用性,能够快速地存储、搜索和分析海量数据,可用于各种不同的应用程序。

接下来介绍一下Springboot整合ES时常见的一些操作。

resources-application.yml

spring:
  elasticsearch:
    uris: http://localhost:9200

service

EsService.java

package cn.halashuo.es.service;

import org.elasticsearch.search.builder.SearchSourceBuilder;

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

public interface EsService {

    Set<String> getAllIndex();

    Map<String, String> getMapping(String indexName);

    List<Map<String, Object>> search(String indexName, SearchSourceBuilder searchSourceBuilder);
}

impl

EsServiceImpl.java

package cn.halashuo.es.service.impl;

import cn.halashuo.es.service.EsService;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.GetAliasesResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetMappingsRequest;
import org.elasticsearch.client.indices.GetMappingsResponse;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class EsServiceImpl implements EsService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    /**
     * 获取所有索引
     **
     * @return
     */
    @Override
    public Set<String> getAllIndex() {
        GetAliasesRequest request = new GetAliasesRequest();
        GetAliasesResponse response = null;
        try {
            response = restHighLevelClient.indices().getAlias(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        Map<String, Set<AliasMetadata>> aliases = response.getAliases();
        Set<String> strings = aliases.keySet();
        return strings;
    }


    /**
     * 获取索引全部字段及字段type
     **
     * @param indexName 索引名
     * @return
     */
    @Override
    public Map<String, String> getMapping(String indexName){
        GetMappingsRequest request = new GetMappingsRequest().indices(indexName);
        GetMappingsResponse response = null;
        try {
            response = restHighLevelClient.indices().getMapping(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Map<String, Object> mappings = response.mappings().get(indexName).getSourceAsMap();
        Map<String, Map<String, Object>> properties = (Map<String, Map<String, Object>>) mappings.get("properties");

        Map<String, String> result = new HashMap<>();
        properties.keySet().forEach(key -> {
            String value = properties.get(key).get("type").toString();
            System.out.println(key);
            result.put(key, value);
        } );

        return result;
    }


    /**
     * 查询
     **
     * @param indexName 索引名称
     * @param searchSourceBuilder 查询条件
     * @return List中的每个Map都是一个doc
     */
    @Override
    public List<Map<String, Object>> search(String indexName, SearchSourceBuilder searchSourceBuilder) {
        SearchRequest searchRequest = new SearchRequest(indexName);
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = null;
        try {
            search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        SearchHit[] hits = search.getHits().getHits();
        List<Map<String, Object>> result = new ArrayList<>();
        Arrays.stream(hits).iterator().forEachRemaining(oneDoc -> {
            Map<String, Object> sourceAsMap = (Map<String, Object>) oneDoc.getSourceAsMap();
            System.out.println(sourceAsMap);
            result.add(sourceAsMap);
        });
        return result;
    }
}

controller

EsController.java

package cn.halashuo.es.controller;

import cn.halashuo.es.service.EsService;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class EsController {

    @Autowired
    private EsService esService;

    @GetMapping("/getAllIndex")
    public Set<String> getAllIndex(){
        return esService.getAllIndex();
    }

    @GetMapping("/getMapping/{indexName}")
    public Map<String, String> getMapping(@PathVariable("indexName") String indexName){
        return esService.getMapping(indexName);
    }

    @GetMapping("/getAllData/{indexName}")
    public List<Map<String, Object>> getAllData(@PathVariable String indexName) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
                .size(100);
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        esService.search(indexName, searchSourceBuilder);
        return esService.search(indexName, searchSourceBuilder);
    }

    @GetMapping("/test")
    public List<Map<String, Object>> test() {

        QueryBuilder queryBool = QueryBuilders.boolQuery()
                .must(QueryBuilders.termQuery("field1", "value1"));
                //.mustNot(QueryBuilders.termQuery("field2", "value2"))
                //.should(QueryBuilders.termQuery("field3", "value3"));

        QueryBuilder queryRange = QueryBuilders.rangeQuery("timestamp")
                .gte(1678267008730L) // 大于等于
                .lte(1678267820722L); // 小于等于

        // 模糊搜索
        // *表示匹配任意多个字符(包括零个字符)
        // ?表示匹配任意单个字符
        WildcardQueryBuilder queryWildcard = QueryBuilders.wildcardQuery("field1", "*h5*");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
                .query(queryBool)
                .query(queryRange)
                .query(queryWildcard)
                //.collapse(new CollapseBuilder("dataStatistics")) // 根据字段去重
                .from(0) // 设置分页
                .size(500) // 默认只显示10个
                .fetchSource(new String[]{"field1", "field2", "field3", "timestamp"}, null) // 只返回以上字段
                .sort(SortBuilders.fieldSort("timestamp").order(SortOrder.ASC)) // 根据字段排序(DESC为从大到小)
                ;

        return esService.search("IndexName", searchSourceBuilder);
    }
}

EsApplication.java

package cn.halashuo.es;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class EsApplication {

    public static void main(String[] args) {
        SpringApplication.run(EsApplication.class, args);
    }
}
最后修改:2023 年 04 月 20 日
如果觉得我的文章对你有用,请随意赞赏