当前位置: 代码网 > it编程>编程语言>Java > SpringBoot整合Elasticsearch

SpringBoot整合Elasticsearch

2024年08月06日 Java 我要评论
本文使用第一种方式。使用官方推荐的RestHighLevelClient操作ES。由于版本兼容问题,请选择和Elasticsearch对应的Java客户端版本。

springboot整合elasticsearch

springboot整合elasticsearch有以下几种方式:

  1. 使用官方的elasticsearch java客户端进行集成
    • 通过添加elasticsearch java客户端的依赖,可以直接在spring boot应用中使用原生的elasticsearch api进行操作。
    • 参考文档
  2. 使用spring data elasticsearch进行集成
    • spring data elasticsearch是spring data项目的一部分,提供了更高级的抽象和易用性,可以简化与elasticsearch的交互。
    • 通过添加spring data elasticsearch的依赖,可以使用repository接口和注解来定义和执行crud操作。
    • 官方文档

本文使用第一种方式。使用官方推荐的resthighlevelclient操作es。由于版本兼容问题,请选择和elasticsearch对应的java客户端版本。

使用官方的elasticsearch java客户端进行集成

依赖

在这里插入图片描述
从官方文档可以知道需要导入org.elasticsearch:elasticsearch和org.elasticsearch.client:elasticsearch-rest-client。


    <dependencies>
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-data-elasticsearch</artifactid>
            <version>2.2.2.release</version>
        </dependency>

        <dependency>
            <groupid>org.elasticsearch</groupid>
            <artifactid>elasticsearch</artifactid>
            <version>7.4.2</version>
        </dependency>

        <dependency>
            <groupid>org.elasticsearch.client</groupid>
            <artifactid>elasticsearch-rest-high-level-client</artifactid>
            <version>7.4.2</version>
        </dependency>

        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-test</artifactid>
            <scope>test</scope>
        </dependency>

    </dependencies>

配置

@configuration
public class esconfig {

    /**
     * 解决netty引起的issue
     */
    @postconstruct
    void init() {
        system.setproperty("es.set.netty.runtime.available.processors", "false");
    }


    @bean
    public resthighlevelclient getrestclient() {

        resthighlevelclient resthighlevelclient = new resthighlevelclient(restclient
                .builder(new httphost("192.168.200.200", 9200, "http")));
        return resthighlevelclient;
    }

}

创建索引

    @autowired
    private resthighlevelclient resthighlevelclient;

    /**
     * 创建索引
     */
    @test
    public void createindex1() {
        string result = "创建成功";
        createindexrequest createindexrequest = new createindexrequest("stu");
        try {
            createindexresponse createindexresponse = resthighlevelclient.indices().create(createindexrequest, requestoptions.default);

            if (!createindexresponse.isacknowledged()){
                result = "创建失败";
            }else{
                result = "索引已经存在";
            }
        } catch (ioexception e) {
            e.printstacktrace();
            result = "接口异常";
        }

        system.out.println(result);
    }
   /**
     * 创建索引同时创建映射关系
     * 如索引存在:新增文档数据;如果索引不存在:创建一条索引
     */
    @test
    public void createindex2() {
        hashmap<string, object> map = new hashmap<>();
        map.put("user", "kimchyrw");
        map.put("postdate", new date());
        map.put("message", "trying out elasticsearch");

        indexrequest request = new indexrequest("posts")
                .id("2").source(map, xcontenttype.json);

        try {
            //响应信息
            indexresponse indexresponse = resthighlevelclient.index(request, requestoptions.default);
            string index = indexresponse.getindex();
            string id = indexresponse.getid();
            system.out.println("index: " + index + " id: " + id);
            //创建索引还是更新索引
            if (indexresponse.getresult() == docwriteresponse.result.created) {
                system.out.println("created.....");
            } else if (indexresponse.getresult() == docwriteresponse.result.updated) {
                system.out.println("updated....");
            }
            //校验分片信息
            replicationresponse.shardinfo shardinfo = indexresponse.getshardinfo();
            if (shardinfo.gettotal() != shardinfo.getsuccessful()){

            }
            if (shardinfo.getfailed() > 0) {
                for (replicationresponse.shardinfo.failure failure :shardinfo.getfailures()) {
                    string reason = failure.reason();
                    system.out.println("reason: " + reason);
                }
            }
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }

更新文档中的数据

    /**
     * 更新一行数据
     */
    @test
    public void updatedoc() {
        //更新的数据
        hashmap<string, object> map = new hashmap<>();
        map.put("updated", new date());
        map.put("user", "kimchyrw");
        map.put("reason", "daily update");
        updaterequest updaterequest = new updaterequest("posts", "2")
                .doc(map);
        try {
            updateresponse updateresponse = resthighlevelclient.update(updaterequest, requestoptions.default);
            string index = updateresponse.getindex();
            string id = updateresponse.getid();
            long version = updateresponse.getversion();
            if (updateresponse.getresult() == docwriteresponse.result.created) {
                system.out.println("created");
            } else if (updateresponse.getresult() == docwriteresponse.result.updated) {
                system.out.println("updated");
            } else if (updateresponse.getresult() == docwriteresponse.result.deleted) {
                system.out.println("deleted");
            } else if (updateresponse.getresult() == docwriteresponse.result.noop) {
                system.out.println("noop");
            }
        } catch (ioexception e) {
            e.printstacktrace();
        }

    }

查询

   /**
     * 根据id查询document
     */
    @test
    public void getapi() {
        getrequest getrequest = new getrequest("posts", "1");
        //可选参数
        //禁用源检索,默认启用,开启后检索不到数据
       // getrequest.fetchsourcecontext(fetchsourcecontext.do_not_fetch_source);

        try {
            getresponse getresponse = resthighlevelclient.get(getrequest, requestoptions.default);
            string index = getresponse.getindex();
            string id = getresponse.getid();
            system.out.println("index: " + index + " id: " + id);
            if (getresponse.isexists()) {
                long version = getresponse.getversion();
                string sourceasstring = getresponse.getsourceasstring();
                map<string, object> sourceasmap = getresponse.getsourceasmap();
                byte[] sourceasbytes = getresponse.getsourceasbytes();
                system.out.println("version: " + version);
                system.out.println("sourceasmap: " + sourceasmap);
                system.out.println("sourceasbytes: " + arrays.tostring(sourceasbytes));
                system.out.println("sourceasstring: " + sourceasstring);
            }
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
   /**
     * 根据指定字段查询document
     */
    @test
    public void testsearch2() {
        searchrequest searchrequest = new searchrequest("posts");
        searchsourcebuilder searchsourcebuilder = new searchsourcebuilder();
        //根据指定字段查询
        searchsourcebuilder.query(querybuilders.termquery("user", "kimchy"));
        //分页查询记录
        searchsourcebuilder.from(0);
        searchsourcebuilder.size(5);
        //设置超时时间
       // searchsourcebuilder.timeout(new timevalue(60, timeunit.seconds));
        //按字段排序或者按评分排序
        searchsourcebuilder.sort(new scoresortbuilder().order(sortorder.desc));
        searchsourcebuilder.sort(new fieldsortbuilder("_id").order(sortorder.asc));

        //结果高亮

        //查询部分字段
        searchsourcebuilder.fetchsource(new string[]{"user"}, new string[]{"user1"});
        searchrequest.source(searchsourcebuilder);

        try {
            searchresponse searchresponse = resthighlevelclient.search(searchrequest, requestoptions.default);
            reststatus status = searchresponse.status();
            timevalue took = searchresponse.gettook();
            boolean terminatedearly = searchresponse.isterminatedearly();
            boolean timedout = searchresponse.istimedout();

            searchhits hits = searchresponse.gethits();
            totalhits totalhits = hits.gettotalhits();
            long numhits = totalhits.value;
            totalhits.relation relation = totalhits.relation;
            float maxscore = hits.getmaxscore();
            system.out.println("hits: " + hits + " totalhits: " + totalhits + " numhits: " + numhits + " maxscore: " + maxscore);
            searchhit[] searchhits = hits.gethits();
            for (searchhit hit: searchhits) {
                string id = hit.getid();
                system.out.println("id: " + id);
                string sourceasstring = hit.getsourceasstring();
                system.out.println(sourceasstring);
            }

        } catch (ioexception e) {
            e.printstacktrace();
        }
    }

使用spring data elasticsearch进行集成

依赖

        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-data-elasticsearch</artifactid>
        </dependency>
        
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-data-jpa</artifactid>
        </dependency>

创建实体类

启动后会自动创建索引foodie-items

@data
@document(indexname = "foodie-items", createindex = true)
public class items {

    @javax.persistence.id
    private string id;

    @field(type = fieldtype.text)
    private string itemid;

    @field(type = fieldtype.text)
    private string itemname;

    @field(type = fieldtype.text)
    private string imgurl;

    @field(type = fieldtype.double)
    private integer price;

    @field(type = fieldtype.integer)
    private integer sellcounts;

    @field(type = fieldtype.integer)
    private integer catid;

    @field(type = fieldtype.integer)
    private integer rootcatid;

    @field(type = fieldtype.integer)
    private integer onoffstatus;

    @field(type = fieldtype.date, format = dateformat.basic_date_time)
    private date createdtime;

    @field(type = fieldtype.date, format = dateformat.basic_date_time)
    private date updatedtime;

    @field(type = fieldtype.text)
    private string content;

}

继承接口

继承elasticsearchrepository接口后,可以在接口中自定义方法,也可以使用接口提供的方法进行查询。和jpa的使用是类似的。

/**
 * 在实体类上使用注解,然后继承elasticsearchrepository接口, 启动后会自动创建索引
 */
@repository("esfooditemsrepository")
public interface esfooditemsrepository extends elasticsearchrepository<items, string> {
}

elasticsearch operations使用

    @autowired
    private elasticsearchoperations elasticsearchoperations;

    @test
    public void test2() {
        items items = elasticsearchoperations.get("1", items.class);
        system.out.println("items: " + items);
    }

elasticsearch operations

参考

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com