淘先锋技术网

首页 1 2 3 4 5 6 7

简介

 https://www.elastic.co/cn/what-is/elasticsearch 全文搜索属于最常见的需求,开源的 Elasticsearch 是目前全文搜索引擎的首选。 它可以快速地储存、搜索和分析海量数据。维基百科、Stack Overflow、Github 都采用它 Elastic 的底层是开源库 Lucene。但是,你没法直接用 Lucene,必须自己写代码去调用它的 接口。Elastic 是 Lucene 的封装,提供了 REST API 的操作接口,开箱即用。 REST API:天然的跨平台。

官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html

官方中文:https://www.elastic.co/guide/cn/elasticsearch/guide/current/foreword_id.html

社区中文: https://es.xiaoleilu.com/index.html http://doc.codingdict.com/elasticsearch/0/

 参考官网文档:Java High Level REST Client | Java REST Client [7.17] | Elastic

 1.引入依赖

         <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.4.2</version>
        </dependency>

 引入依赖如果出现版本不匹配问题:

 <properties>
        <java.version>1.8</java.version>
        <elasticsearch.version>7.4.2</elasticsearch.version>
 </properties>

2.配置

@Configuration
public class GulimallElasticsearchConfig {
    public static final RequestOptions COMMON_OPTIONS;
    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
//        builder.addHeader("Authorization", "Bearer " + TOKEN);
//        builder.setHttpAsyncResponseConsumerFactory(
//                new HttpAsyncResponseConsumerFactory
//                        .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));
        COMMON_OPTIONS = builder.build();
    }
    @Bean
    public RestHighLevelClient esRestClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        //集群管理时可以设置多个
                        new HttpHost("localhost", 9200, "http")));
        return client;
    }
}

 测试

1.测试存储数据到ES

@RunWith(SpringRunner.class)
@SpringBootTest
public class GulimallSearchApplicationTests {
    @Resource
    RestHighLevelClient client;
    
    //保存
    @Test
    public void indexSave() throws IOException {
        IndexRequest request = new IndexRequest("users");
        User user  = new User();
        user.setUsername("张三");
        user.setAddress("北京");
        user.setAge(23);
        String s = JSON.toJSONString(user);
        request.source(s, XContentType.JSON);
        client.index(request, GulimallElasticsearchConfig.COMMON_OPTIONS);
    }
    @Data
    class User{
        private String username;
        private Integer age;
        private String address;
    }
}

 2.测试检索操作

@Test
    public void search() throws IOException {
        //创建检索请求
        SearchRequest searchRequest = new SearchRequest();
        //指定索引
        searchRequest.indices("bank");
        //指定检索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("address","mill"));
        TermsAggregationBuilder ageAgg = AggregationBuilders.terms("ageAgg").field("age").size(10);
        AvgAggregationBuilder avgBlance = AggregationBuilders.avg("avgBlance").field("balance");
        searchSourceBuilder.aggregation(avgBlance);
        searchSourceBuilder.aggregation(ageAgg);
        System.out.println("检索条件为:"+searchSourceBuilder.toString());
        searchRequest.source(searchSourceBuilder);
        //执行检索
        SearchResponse search = client.search(searchRequest, GulimallElasticsearchConfig.COMMON_OPTIONS);
        System.out.println("检索结果为:"+search.toString());
        //分析检索结果
       // Map map = JSON.parseObject(search.toString(), Map.class);
        SearchHits hits = search.getHits();
        SearchHit[] searchHits = hits.getHits();
        for(SearchHit hit : searchHits){
            String sourceAsString = hit.getSourceAsString();
            Account account = JSON.parseObject(sourceAsString, Account.class);
            System.out.println(account.toString());
        }
        //获取聚合信息
        Aggregations aggregations = search.getAggregations();
        Terms ageAgg1 = aggregations.get("ageAgg");
        for(Terms.Bucket bucket:ageAgg1.getBuckets()){
            String keyAsString = bucket.getKeyAsString();
            System.out.println("年齡:"+keyAsString+"==>"+bucket.getDocCount());
        }



    }