Spring整合ElasticSearch 实现增删改,高亮,聚合查询

Spring整合ElasticSearch 实现增删改,高亮,聚合查询,第1张

Spring整合ElasticSearch 实现增删改,高亮,聚合查询 1.创建RestHighLevelClient对象
    @Bean
        public RestHighLevelClient restHighLevelClient(){
       return new RestHighLevelClient(RestClient.builder(new HttpHost(
                "127.0.0.1",9200
        )));
    }
2.索引 *** 作
public class IndexUtils {

    private static RestHighLevelClient client=(RestHighLevelClient) SpringUtils.app.getBean(RestHighLevelClient.class);;


    private IndexUtils(RestHighLevelClient restHighLevelClient) {

    }

    
    public static Collection getIndexAll() throws IOException {
        //获取索引客户端
        IndicesClient indices = client.indices();

        GetAliasesRequest request=new GetAliasesRequest();

        GetAliasesResponse alias = indices.getAlias(request, RequestOptions.DEFAULT);

        Map aliasAliases = alias.getAliases();

        Set indexAlias = aliasAliases.keySet();

        return indexAlias;
    }

    //创建索引
    public static Boolean createIndex(String indexName) throws IOException {

        CreateIndexRequest createIndex=new CreateIndexRequest(indexName);

        boolean acknowledged = false;
        try {
            CreateIndexResponse response = client.indices().create(createIndex, RequestOptions.DEFAULT);

            acknowledged = response.isAcknowledged();
        } catch (Exception e) {
            return false;
        }

        return acknowledged;
    }

    //删除索引
    public static Boolean deleteIndex(String indexName){
        DeleteIndexRequest deleteIndex =new DeleteIndexRequest(indexName);

        boolean acknowledged ;

        try {
            AcknowledgedResponse delete = client.indices().delete(deleteIndex, RequestOptions.DEFAULT);

             acknowledged =   delete.isAcknowledged();

        } catch (Exception e) {
           return false;
        }

        return acknowledged;
    }

    //判断索引是否存在
    public static Boolean existIndex(String indexName) throws IOException {
        GetIndexRequest getIndexRequest=new GetIndexRequest(indexName);
        boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        return exists;
    }

    //创建索引后添加映射
    public static Boolean creatMapping(String indexName) throws IOException {

        PutMappingRequest putMappingRequest = new PutMappingRequest(indexName);
        putMappingRequest.source("{n" +
                "  "properties":{n" +
                "    "id":{n" +
                "      "index":false,n" +
                "      "store":false,n" +
                "      "type":"integer"n" +
                "    },n" +
                "    "name":{n" +
                "      "index":true,n" +
                "      "store":false,n" +
                "      "type":"text",n" +
                "      "analyzer":"ik_max_word"n" +
                "    },n" +
                "    "age":{n" +
                "      "index":true,n" +
                "      "store":false,n" +
                "      "type":"integer"n" +
                "    },n" +
                "        "address":{n" +
                "     "index": true,n" +
                "     "store": true,n" +
                "     "analyzer": "ik_max_word",n" +
                "     "type": "text"n" +
                "    }n" +
                "  }n" +
                "}",XContentType.JSON);


        AcknowledgedResponse acknowledgedResponse = client.indices().putMapping(putMappingRequest, RequestOptions.DEFAULT);

        return acknowledgedResponse.isAcknowledged();
    }

    //创建索引时建立映射(Map方式)
    public static Boolean createIndexAndMappingMap(String indexName) throws IOException {

        CreateIndexRequest createIndexRequest=new CreateIndexRequest(indexName);

        Map map=new HashMap<>();

        Map propertiesMap=new HashMap<>();

        Map idMap =new HashMap();
        idMap.put("index",false);
        idMap.put("store",false);
        idMap.put("type","integer");
        propertiesMap.put("id",idMap);


        Map nameMap =new HashMap();
        nameMap.put("index",true);
        nameMap.put("store",false);
        nameMap.put("type","text");
        nameMap.put("analyzer","ik_max_word");
        propertiesMap.put("name",nameMap);

        Map ageMap =new HashMap();
        ageMap.put("index",false);
        ageMap.put("store",false);
        ageMap.put("type","integer");
        propertiesMap.put("age",ageMap);

        map.put("properties",propertiesMap);
        createIndexRequest.mapping("_doc",map);
        CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        return createIndexResponse.isAcknowledged();
    }


    //创建索引时建立映射
    public static Boolean createIndexAndMapping(String indexName) throws IOException {
        CreateIndexRequest createIndexRequest=new CreateIndexRequest(indexName);
        createIndexRequest.mapping("mapping","{n" +
                "  "properties":{n" +
                "    "id":{n" +
                "      "index":false,n" +
                "      "store":false,n" +
                "      "type":"integer"n" +
                "    },n" +
                "    "name":{n" +
                "      "index":true,n" +
                "      "store":false,n" +
                "      "type":"text",n" +
                "      "analyzer":"ik_max_word"n" +
                "    },n" +
                "    "age":{n" +
                "      "index":true,n" +
                "      "store":false,n" +
                "      "type":"integer"n" +
                "    },n" +
                "        "address":{n" +
                "     "index": true,n" +
                "     "store": true,n" +
                "     "analyzer": "ik_max_word",n" +
                "     "type": "text"n" +
                "    }n" +
                "  }n" +
                "}",XContentType.JSON);
        CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);

        return createIndexResponse.isAcknowledged();
    }


}
3.文档 *** 作
public class DocUtils {

    private static RestHighLevelClient client=(RestHighLevelClient) SpringUtils.app.getBean(RestHighLevelClient.class);;


    private DocUtils(RestHighLevelClient restHighLevelClient) {

    }

    
    public static Object addDocOfMap(String indexName) throws IOException {
        //指定 *** 作的索引库
        IndexRequest indexRequest=new IndexRequest(indexName);

        Map map=new HashMap<>();
        map.put("age",19);
        map.put("name","王大拿");
        map.put("id","001");

        indexRequest.source(map).id("4");

        IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);

        return index.getResult();
    }

    
    public static Object addDocOfObject(String indexName) throws IOException {

        IndexRequest indexRequest=new IndexRequest(indexName);

        Person person = new Person(2,"张三",15);

        String s = JSON.toJSonString(person);

        indexRequest.source(s, XContentType.JSON);

        IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);

        return index.getResult();
    }

    
    public static Object getDocById(String indexName) throws IOException {

        GetRequest getRequest=new GetRequest(indexName);

        getRequest.id("1");

        GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);

        return documentFields.getSource();
    }

    
    public static Object deleteDocById(String indexName) throws IOException {

        DeleteRequest deleteRequest=new DeleteRequest(indexName);

        deleteRequest.id("1");

        DeleteResponse delete = client.delete(deleteRequest, RequestOptions.DEFAULT);

        return delete.getResult();
    }


    
    public static BulkResponse bulk(String indexName) throws IOException {

        BulkRequest bulkRequest=new BulkRequest();


        IndexRequest indexRequest = new IndexRequest(indexName);
        //添加文档二
        Person person2 = new Person(2222, "张二11111", 22);
        String s2 = JSON.toJSonString(person2);
        indexRequest.source(s2,XContentType.JSON);
        bulkRequest.add(indexRequest);
        //添加文档三
        Person person3 = new Person(32222, "三111111", 3);
        String s3 = JSON.toJSonString(person3);
        indexRequest.source(s3,XContentType.JSON);
        bulkRequest.add(indexRequest);

//        删除文档二
        DeleteRequest deleteRequest=new DeleteRequest(indexName);
        deleteRequest.id("2");
        bulkRequest.add(deleteRequest);

        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);

        return bulk;

    }
}
4.查询
public class SearchUtils {
    private static RestHighLevelClient client = (RestHighLevelClient) SpringUtils.app.getBean(RestHighLevelClient.class);

    private static SearchRequest searchRequest = new SearchRequest("goods");

    private SearchUtils(RestHighLevelClient restHighLevelClient) {

    }

    
    public static void parseSearchResponse(SearchResponse search) {
        Timevalue took = search.getTook();
        System.out.println("查询时间 : " + took);
        //命中的内容
        SearchHits hits = search.getHits();
        TotalHits totalHits = hits.getTotalHits();
        long value = totalHits.value;
        System.out.println("总命中数:" + value);
        float maxScore = hits.getMaxScore();
        System.out.println("最高分数:" + maxScore);
        //查询的结果
        for (SearchHit hit : hits.getHits()) {
            Map sourceAsMap = hit.getSourceAsMap();
            System.out.println(sourceAsMap);
        }

        //查询聚合文档
        Aggregations aggregations = search.getAggregations();
        if (null!=aggregations){
            ParsedAvg aggregation = aggregations.get("三星平均价");

            System.out.println("三星平均价"+ aggregation.getValue());
        }


        //获取高亮查询结果
        for (SearchHit hit : hits.getHits()) {
            Map highlightFields = hit.getHighlightFields();
            System.out.println("highlightFields = " + highlightFields);
            for (HighlightField highlightField : highlightFields.values()) {
                System.out.println(highlightField.fragments()[0]);
            }
        }
    }

    public static void searchAll() throws IOException {

        //创建查询条件对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
//        searchSourceBuilder.size(1);
//        searchSourceBuilder.from(20);
        searchRequest.source(searchSourceBuilder);

        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);

        parseSearchResponse(search);
    }

    public static void searchMatch() throws IOException {

        //创建查询条件对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        searchSourceBuilder.query(QueryBuilders.matchQuery("title","手机"));
        searchRequest.source(searchSourceBuilder);

        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);

        parseSearchResponse(search);
    }

    public static void term() throws IOException {

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        searchSourceBuilder.query(QueryBuilders.termQuery("brandName","三星"));

        SearchRequest source = searchRequest.source(searchSourceBuilder);

        SearchResponse search = client.search(source, RequestOptions.DEFAULT);

        parseSearchResponse(search);
    }

    public static void terms() throws IOException {

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        searchSourceBuilder.query(QueryBuilders.termsQuery("brandName","三星","华为"));

        SearchRequest source = searchRequest.source(searchSourceBuilder);

        SearchResponse search = client.search(source, RequestOptions.DEFAULT);

        parseSearchResponse(search);
    }

    public static void Wildcard() throws IOException {

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        searchSourceBuilder.query(QueryBuilders.wildcardQuery("title","3*"));

        SearchRequest source = searchRequest.source(searchSourceBuilder);

        SearchResponse search = client.search(source, RequestOptions.DEFAULT);

        parseSearchResponse(search);
    }

    public static void PrefixQuery() throws IOException {

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        searchSourceBuilder.query(QueryBuilders.prefixQuery("title","阿"));

        SearchRequest source = searchRequest.source(searchSourceBuilder);

        SearchResponse search = client.search(source, RequestOptions.DEFAULT);

        parseSearchResponse(search);
    }

    public static void Range() throws IOException {

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        RangeQueryBuilder query=QueryBuilders.rangeQuery("price");
        query.gt(100);
        query.lt(1000);

        SearchSourceBuilder sourceBuilder = searchSourceBuilder.query(query);
        sourceBuilder.size(30);
        sourceBuilder.sort("price", SortOrder.DESC);
        SearchRequest source = searchRequest.source(searchSourceBuilder);

        SearchResponse search = client.search(source, RequestOptions.DEFAULT);

        parseSearchResponse(search);
    }

    public static void QueryStirng() throws IOException {

        SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();

        QueryBuilder query=QueryBuilders.queryStringQuery("联通")
                .field("title");


        searchSourceBuilder.query(query);

        searchRequest.source(searchSourceBuilder);

        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);

        parseSearchResponse(search);

    }

    public static void bool() throws IOException {

        SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();


        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("price");
        rangeQueryBuilder.gt(2000);
        rangeQueryBuilder.lt(5000);

        QueryBuilder query=QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("brandName","华为"))
                .filter(QueryBuilders.termQuery("categoryName","手机"))
                .filter(rangeQueryBuilder);




        searchSourceBuilder.query(query);

        searchRequest.source(searchSourceBuilder);

        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);

        parseSearchResponse(search);
    }

    
    public static void aggs() throws IOException {

        SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();

        searchSourceBuilder.query(QueryBuilders.matchQuery("brandName","三星"));

        searchSourceBuilder.aggregation(AggregationBuilders.avg("三星平均价").field("price"));

        searchRequest.source(searchSourceBuilder);

        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);

        parseSearchResponse(search);
    }

    public static void HighLightQuery() throws IOException {
        SearchSourceBuilder sourceBuild=new SearchSourceBuilder();

        QueryBuilder query=QueryBuilders.matchQuery("brandName","三星");

        sourceBuild.query(query);

        HighlightBuilder hlightBuilder=new HighlightBuilder();
        hlightBuilder.field("brandName");
        hlightBuilder.preTags("");
        hlightBuilder.postTags("");

        sourceBuild.highlighter(hlightBuilder);

        searchRequest.source(sourceBuild);

        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        parseSearchResponse(search);
    }

}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5716942.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存