Spring Boot 整合 Elasticsearch

ElasticSearch 是一个基于 Lucene 的搜索服务器,是一个分布式、可扩展、实时的搜索与数据分析引擎,它能从项目一开始就赋予你的数据以搜索、分析和探索的能力,基于 RESTful web 接口。ElasticSearch 是用 Java 开发的,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。

使用 ElasticSearch 需要添加 Maven 依赖:


<dependency>
    <groupId>org.elasticsearchgroupId>
    <artifactId>elasticsearchartifactId>
    <version>5.6.15version>
dependency>
<dependency>
    <groupId>org.elasticsearch.clientgroupId>
    <artifactId>transportartifactId>
    <version>5.6.15version>
dependency>

在 JavaConfig 中注册 bean 即集成成功:

@Bean
public TransportClient getTransportClient() throws UnknownHostException {
    //ES默认TCP端口是9300
    InetSocketTransportAddress node = new InetSocketTransportAddress(
            InetAddress.getByName("192.168.2.20"), 9300
    );
    Settings settings = Settings.builder()
            .put("cluster.name", "es")
            .build();
    TransportClient client = new PreBuiltTransportClient(settings);
    //多个client多次new InetSocketTransportAddress,多次添加就行
    client.addTransportAddress(node);
    return client;
}

1.Elasticsearch基本操作

操作 Elasticsearch 只需要注入 TransportClient 就可以了:

@Resource
private TransportClient client;

查询:

GetResponse response = client.prepareGet("book", "techbook", "1").get();
System.out.println(response.getSource()); //输出查询结果

创建:

XContentBuilder builder = XContentFactory.jsonBuilder()
        .startObject()
        .field("title", "java8")
        .field("author", "Tom")
        .field("word_count", 1000)
        .endObject();
IndexResponse response = client.prepareIndex("book", "techbook")
        .setSource(builder)
        .get();                           
System.out.println(response.getResult() + ", id=" + response.getId()); //输出创建结果,成功返回 CREATED

删除:

DeleteResponse response = client.prepareDelete("book", "techbook", "1").get();
System.out.println(response.getResult()); //输出删除结果,成功返回 DELETED

修改:

UpdateRequest request    = new UpdateRequest("book", "techbook", "1");
XContentBuilder builder = XContentFactory.jsonBuilder()
        .startObject()
        .field("title", "java9")
        .endObject();
request.doc(builder);
UpdateResponse response = client.update(request).get();
System.out.println(response.getResult()); //输出修改结果,成功返回 UPDATED

复合查询:

BoolQueryBuilder boolQuery = QueryBuilders.boolQuery()
        .must(QueryBuilders.matchQuery("author", "Tom"));
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("word_count")
        .from("1000")
        .to("5000");
boolQuery.filter(rangeQuery);
SearchResponse response = client.prepareSearch("book")
        .setTypes("techbook")
        .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
        .setQuery(boolQuery)
        .setFrom(0)
        .setSize(10)
        .get();
System.out.println(response); //输出复合查询结果

你可能感兴趣的:(搜索技术,Spring,Boot,Elasticsearch)