欢迎投稿

今日深度:

Elasticsearch 系列指南(四)——Java集成,elasticsearchjava

Elasticsearch 系列指南(四)——Java集成,elasticsearchjava


前面我们已经讲了Elasticsearch安装、分词、基本查询等,但在我们实际的开发中往往是将其集成在的项目当中,现在我们就以Java为例进行es的集成,本次所用的框架是Spring Boot,有对Spring Boot不了解的可以找资料了解下,这将会成为下一代的主流框架,Java集成es有两种方式,一种是基于Spring Data的方式,另一种是原生的TransportClient客户端连接方式,推荐使用前一种,因为前一种可以像写Sql语句一样去写增删查改,这里我们以第二种方式来实现Elasticsearch6.1.1的集成。

引入pom依赖

<!-- 添加es的依赖包 -->
<dependency>
	<groupId>org.elasticsearch</groupId>
	<artifactId>elasticsearch</artifactId>
	<version>6.1.1</version>
</dependency>

<dependency>
	<groupId>org.elasticsearch.client</groupId>
	<artifactId>transport</artifactId>
	<version>6.1.1</version>
</dependency>

建立客户端连接

新建ESConfig类
package com.xiaoma.configuration.es;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * es全文检索配置
 * Created by mj on 2018/1/15.
 */
@Configuration
public class ESConfig {

    @Bean
    public TransportClient client() throws UnknownHostException {

        //设置es连接地址 创建三个节点实例
        TransportAddress node1 = new TransportAddress(
                InetAddress.getByName("localhost"),
                9300
        );
        TransportAddress node2 = new TransportAddress(
                InetAddress.getByName("localhost"),
                9301
        );
        TransportAddress node3 = new TransportAddress(
                InetAddress.getByName("localhost"),
                9302
        );

        TransportClient client = null;
        try {
            //设置集群的参数配置(根据需要设置其他参数)
            Settings settings = Settings.builder()
                    .put("cluster.name","myblog")
                    .build();
            //构造TransportClient实例
            client = new PreBuiltTransportClient(settings);
            client.addTransportAddress(node1);
            client.addTransportAddress(node2);
            client.addTransportAddress(node3);
        }catch (Exception e){
            e.printStackTrace();
        }

        return client;
    }

}
@Configuration:表明这是一个配置类 @Bean:表明注入一个bean
基本操作 接下来我们进行一些基本的增删改查操作,首先我们新建一个ESController类
  • 根据id查询接口开发
@RestController
public class ESController {

    //注入TransportClient
    @Autowired
    private TransportClient client;

    @GetMapping("get/people/man")
    @ResponseBody
    public RetResult getById(@RequestParam(name = "id",defaultValue = "") String id){

        String code = CommConstant.GWSCOD0000;
        String message = CommConstant.GWSMSG0000;
        //设置获取的索引、类型、id
        GetResponse result = this.client.prepareGet("people","man",id)
                .get();

        return RetResult.setRetDate(code,message,result.getSource());
    }
}
测试 GET请求:http://localhost:8080/get/people/man?id=2 得到结果:
{
    "code": "000",
    "data": {
        "date": "2018-10-30",
        "country": "英国",
        "name": "小花",
        "age": 30
    },
    "extraData": null,
    "message": "success"
}
  • 增加接口开发
    @PostMapping("add/people/man")
    @ResponseBody
    public RetResult add(@RequestParam(name = "name") String name,
                         @RequestParam(name = "country") String country,
                         @RequestParam(name = "age") String age,
                         @RequestParam(name = "date")
                                     @DateTimeFormat(pattern = "yyyy-MM-dd")
                                 Date date){

        String code = CommConstant.GWSCOD0000;
        String message = CommConstant.GWSMSG0000;

        try {
            //es自带json文档转换工具
            XContentBuilder content = XContentFactory.jsonBuilder()
                    .startObject()
                    .field("name",name)
                    .field("country",country)
                    .field("age",age)
                    .field("date",date)
                    .endObject();
            IndexResponse result = this.client.prepareIndex("people","man")
                    .setSource(content)
                    .get();
            return RetResult.setRetDate(code,message,result.getId());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
测试 POST请求:http://localhost:8081/add/people/man 传入参数得到结果:
{
    "code": "000",
    "data": "iHq7CGEBDqEkM1qBVLtN",
    "extraData": null,
    "message": "success
}
  • 删除接口开发
    @DeleteMapping("delete/people/man")
    @ResponseBody
    public RetResult delete(@RequestParam(name = "id") String id){

        String code = CommConstant.GWSCOD0000;
        String message = CommConstant.GWSMSG0000;

        DeleteResponse result = this.client.prepareDelete("people","man",id)
                .get();

        return RetResult.setRetDate(code,message,result.getResult().toString());
    }
测试 DELETE请求:http://localhost:8081/delete/people/man?id=FhBa_2ABVYEInVJlX3kX 得到结果:
{
    "code": "000",
    "data": "DELETED",
    "extraData": null,
    "message": "success"
}
  • 根据id更新接口开发
    @PutMapping("update/people/man")
    @ResponseBody
    public RetResult update(@RequestParam(name = "id") String id,
                            @RequestParam(name = "name",required = false) String name,
                            @RequestParam(name = "age",required = false) String age){

        String code = CommConstant.GWSCOD0000;
        String message = CommConstant.GWSMSG0000;
        //构造更新实例
        UpdateRequest request = new UpdateRequest("people","man",id);
        try {
            //es自带json文档转换工具
            XContentBuilder builder = XContentFactory.jsonBuilder()
                    .startObject();
            if (null != name){
                builder.field("name",name);
            }
            if (null != age){
                builder.field("age",age);
            }
            builder.endObject();
            //设置更新内容
            request.doc(builder);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            UpdateResponse result = this.client.update(request).get();
            return RetResult.setRetDate(code,message,result.getResult().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
测试 PUT请求:http://localhost:8081/update/people/man 传入参数得到结果:
{
    "code": "000",
    "data": "UPDATED",
    "extraData": null,
    "message": "success"
}
  • 复合查询接口开发
    @PostMapping("query/people/man")
    @ResponseBody
    public RetResult query(@RequestParam(name = "name",required = false) String name,
                           @RequestParam(name = "country",required = false) String country,
                           @RequestParam(name = "gt_age",defaultValue = "0") String gtAge,
                           @RequestParam(name = "lt_age",required = false) Integer ltAge){

        String code = CommConstant.GWSCOD0000;
        String message = CommConstant.GWSMSG0000;

        //设置bool查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        if (null != name){
            boolQuery.must(QueryBuilders.matchQuery("name",name));
        }
        if (null != country){
            boolQuery.must(QueryBuilders.matchQuery("country",country));
        }
        //构造范围查询条件
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age")
                .from(gtAge);
        if (null != ltAge && 0 < ltAge){
            rangeQuery.to(ltAge);
        }
        //设置条件过滤
        boolQuery.filter(rangeQuery);

        SearchRequestBuilder builder = this.client.prepareSearch("people")
                .setTypes("man")     //索引类型
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)    //数据量大时用SearchType.QUERY_THEN_FETCH
                .setQuery(boolQuery)  //设置查询条件
                .setFrom(0)
                .setSize(10);
        //查看查询条件创建的格式
        System.out.println(builder);
        //获取查询结果
        SearchResponse response = builder.get();

        List<Map<String,Object>> result = new ArrayList<>();
        for (SearchHit hit : response.getHits()){
            result.add(hit.getSourceAsMap());
        }
        return RetResult.setRetDate(code,message,result);
    }
测试 POST请求:http://localhost:8081/query/people/man 传入参数(这里用的是postman工具)得到结果:
OK到此一些简单的增删查改都已完成,大家可以根据自己的实际需求进行修改,这里给出一个各种查询条件的构建实例,有兴趣的可以去看看点击打开链接

www.htsjk.Com true http://www.htsjk.com/Elasticsearch/36092.html NewsArticle Elasticsearch 系列指南(四)——Java集成,elasticsearchjava 前面我们已经讲了 Elasticsearch 安装、分词、基本查询等,但在我们实际的开发中往往是将其集成在的项目当中,现在我们就以 Ja...
相关文章
    暂无相关文章
评论暂时关闭