欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot框架集成ElasticSearch实现过程示例详解

程序员文章站 2022-11-05 17:56:05
目录依赖与springboot集成配置类实体类测试例子resthighlevelclient直接操作索引操作文档操作检索操作依赖springboot版本:2.4.2

依赖

springboot版本:2.4.2

 <dependencies>
        <!--lombok-->
        <dependency>
            <groupid>org.projectlombok</groupid>
            <artifactid>lombok</artifactid>
            <optional>true</optional>
        </dependency>
		  <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-data-elasticsearch</artifactid>
        </dependency>

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

        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-devtools</artifactid>
            <optional>true</optional>
            <scope>true</scope>
        </dependency>
        <dependency>
            <groupid>com.alibaba</groupid>
            <artifactid>fastjson</artifactid>
            <version>1.2.47</version>
        </dependency>
    </dependencies>
    <dependencymanagement>
        <dependencies>
            <dependency>
                <groupid>org.springframework.cloud</groupid>
                <artifactid>spring-cloud-dependencies</artifactid>
                <version>2020.0.1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupid>com.alibaba.cloud</groupid>
                <artifactid>spring-cloud-alibaba-dependencies</artifactid>
                <version>2021.1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencymanagement>

先了解一下curl方式操作es

SpringBoot框架集成ElasticSearch实现过程示例详解

与springboot集成

配置类

import org.elasticsearch.client.resthighlevelclient;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.data.elasticsearch.client.clientconfiguration;
import org.springframework.data.elasticsearch.client.restclients;
import org.springframework.data.elasticsearch.config.abstractelasticsearchconfiguration;
@configuration
public class elasticsearchconfig extends abstractelasticsearchconfiguration {
    @override
    @bean
    public resthighlevelclient elasticsearchclient() {
        final clientconfiguration clientconfiguration = clientconfiguration.builder()
                .connectedto("localhost:9200")
                .build();
        return restclients.create(clientconfiguration).rest();
    }
}

实体类

import lombok.data;
import org.springframework.data.annotation.id;
import org.springframework.data.elasticsearch.annotations.document;
import org.springframework.data.elasticsearch.annotations.field;
import org.springframework.data.elasticsearch.annotations.fieldtype;
@data
@document(indexname = "product", shards = 3, replicas = 1)
public class product {
    //必须有 id,这里的 id 是全局唯一的标识,等同于 es 中的"_id"
    @id
    private long id;//商品唯一标识
    /**
     * type : 字段数据类型
     * analyzer : 分词器类型
     * index : 是否索引(默认:true)
     * keyword : 短语,不进行分词
     */
    @field(type = fieldtype.text, analyzer = "ik_max_word")
    private string title;//商品名称
    @field(type = fieldtype.keyword)
    private string category;//分类名称
    @field(type = fieldtype.double)
    private double price;//商品价格
    @field(type = fieldtype.keyword, index = false)
    private string images;//图片地址
}

测试例子

@restcontroller
@requestmapping
public class testescontroller {
    @autowired
    private elasticsearchresttemplate elasticsearchresttemplate;
    @resource
    productmapper productmapper;
    @getmapping
    public void createindex() {
        //创建索引,系统初始化会自动创建索引
        system.out.println("创建索引");
    }
    @deletemapping
    public void deleteindex() {
        //创建索引,系统初始化会自动创建索引
        boolean flg = elasticsearchresttemplate.deleteindex(product.class);
        system.out.println("删除索引 = " + flg);
    }
    @postmapping
    public void save(){
        product product = new product();
        product.setid(1l);
        product.settitle("华为手机");
        product.setcategory("手机");
        product.setprice(2999.0);
        product.setimages("http://www.atguigu/hw.jpg");
        productmapper.save(product);
    }
    @putmapping
    public void update(){
        product product = new product();
        product.setid(1l);
        product.settitle("小米 2 手机");
        product.setcategory("手机");
        product.setprice(9999.0);
        product.setimages("http://www.atguigu/xm.jpg");
        productmapper.save(product);
    }
    @getmapping("/findbyid")
    public void findbyid(){
        product product = productmapper.findbyid(1l).get();
        system.out.println(product);
    }
    @getmapping("/findall")
    public void findall(){
        iterable<product> products = productmapper.findall();
        for (product product : products) {
            system.out.println(product);
        }
    }
    //删除
    @deletemapping("/deldocument")
    public void delete(){
        product product = new product();
        product.setid(1l);
        productmapper.delete(product);
    }
    //批量新增
    @postmapping("/addbatch")
    public void saveall(){
        list<product> productlist = new arraylist<>();
        for (int i = 0; i < 10; i++) {
            product product = new product();
            product.setid(long.valueof(i));
            product.settitle("["+i+"]小米手机");
            product.setcategory("手机");
            product.setprice(1999.0+i);
            product.setimages("http://www.atguigu/xm.jpg");
            productlist.add(product);
        }
        productmapper.saveall(productlist);
    }
    //分页查询
    @getmapping("/findbypageable")
    public void findbypageable(){
        //设置排序(排序方式,正序还是倒序,排序的 id)
        sort sort = sort.by(sort.direction.desc,"id");
        int currentpage=0;//当前页,第一页从 0 开始, 1 表示第二页
        int pagesize = 5;//每页显示多少条
        //设置查询分页
        pagerequest pagerequest = pagerequest.of(currentpage, pagesize,sort);
        //分页查询
        page<product> productpage = productmapper.findall(pagerequest);
        for (product product : productpage.getcontent()) {
            system.out.println(product);
        }
    }
}

resthighlevelclient直接操作

这些操作,就是javaapi,和上图中,通过http方式和es交互式类似的

索引操作

/**
 * 这里时测试,开发时:通过 estemplate操作。spring进行了封装
 */
@slf4j
public class esindextestcase {
    public static void main(string[] args) throws ioexception {
        // 创建客户端
        resthighlevelclient esclient = new resthighlevelclient(restclient.builder(new httphost("localhost", 9200)));
        // 创建索引
        // createindexrequest indexrequest = new createindexrequest("book");
        // createindexresponse indexresponse = esclient.indices().create(indexrequest, requestoptions.default);
        // boolean acknowledged = indexresponse.isacknowledged();
        // log.error("响应{}",acknowledged);
        // 查询索引
        // getindexrequest getindexrequest = new getindexrequest("book");
        // getindexresponse getindexresponse = esclient.indices().get(getindexrequest, requestoptions.default);
        // log.info("getaliases:{}",getindexresponse.getaliases());
        // log.info("getmappings:{}",getindexresponse.getmappings());
        // log.info("getsettings:{}",getindexresponse.getsettings());
        // 删除索引
        acknowledgedresponse deleteres = esclient.indices().delete(new deleteindexrequest("book"), requestoptions.default);
        boolean delack = deleteres.isacknowledged();
        log.error("delack:{}",delack);
        esclient.close();
    }
}

文档操作

@slf4j
public class esdocmenttestcase {
    public static void main(string[] args) throws ioexception {
        // 创建客户端
        resthighlevelclient esclient = new resthighlevelclient(restclient.builder(new httphost("localhost", 9200)));
        // 新增文档
        // indexrequest indexrequest = new indexrequest("user");
        // indexrequest.id("1001");       
        // // 准备文档
        // user user = new user();
        // user.setname("张三");
        // user.setage(22);
        // user.setsex("男");        
        // string userjson = jsonobject.tojsonstring(user);
        // indexrequest.source(userjson, xcontenttype.json);
        // indexresponse indexresponse = esclient.index(indexrequest, requestoptions.default);
        // log.error("getresult:==========>:{}",indexresponse.getresult());
        // 批量新增文档
        bulkrequest bulkrequest = new bulkrequest();
        bulkrequest.add(new indexrequest("user").id("2001").source(xcontenttype.json,"name","张三","age","40","sex","男"));
        bulkrequest.add(new indexrequest("user").id("2002").source(xcontenttype.json,"name","222","age","10","sex","女"));
        bulkrequest.add(new indexrequest("user").id("2003").source(xcontenttype.json,"name","33333","age","20","sex","男"));
        bulkrequest.add(new indexrequest("user").id("2004").source(xcontenttype.json,"name","111","age","30","sex","男"));
        bulkrequest.add(new indexrequest("user").id("2005").source(xcontenttype.json,"name","2222","age","31","sex","女"));
        bulkresponse bulkresponse = esclient.bulk(bulkrequest, requestoptions.default);
        log.error("getresult:==========>:{}",bulkresponse.gettook());
        // 更新文档(全量更新,局部更新)

        // updaterequest updaterequest = new updaterequest("user", "1001");
        // updaterequest.doc("sex","dddddd");
        // updateresponse updateresponse = esclient.update(updaterequest, requestoptions.default);
        // log.error("getresult:==========>:{}",updateresponse.getresult());

        // 根据_id查询文档
        // getrequest getrequest = new getrequest("user", "1001");
        // getresponse getresponse = esclient.get(getrequest, requestoptions.default);
        // log.error("getresult:==========>:{}",getresponse.getsource());

        // 根据_id 删除数据
        // deleterequest deleterequest = new deleterequest("user", "1001");
        // deleteresponse deleteresponse = esclient.delete(deleterequest, requestoptions.default);
        // log.error("getresult:==========>:{}",deleteresponse.getresult());

        // 批量删除(和批量新增类似)
        esclient.close();
    }
}

检索操作

@slf4j
public class essearchtest {
    public static void main(string[] args) throws ioexception {
        // 创建客户端
        resthighlevelclient esclient = new resthighlevelclient(restclient.builder(new httphost("localhost", 9200)));
        // 查询所有
        // searchrequest searchrequest = new searchrequest("user");
        // searchsourcebuilder querybuilder = new searchsourcebuilder().query(querybuilders.matchallquery());
        // querybuilder.from(0);
        // querybuilder.size(4);
        // queryabuilder.sort("age", sortorder.desc);
        // searchrequest sourcerequest = searchrequest.source(querybuilder);
        // searchresponse searchresponse = esclient.search(sourcerequest, requestoptions.default);
        // log.error("gethits:======>{}", searchresponse.gethits().gettotalhits());
        // searchresponse.gethits().foreach(hit -> system.out.println(hit.getsourceasstring()));
        // 2-组合查询
        // searchrequest searchrequest = new searchrequest("user");
        // boolquerybuilder boolquerybuilder = querybuilders.boolquery();
        // // 这里就是组合条件。和mysql where 组合类似
        // boolquerybuilder.should(querybuilders.matchquery("age","30"));
        // boolquerybuilder.should(querybuilders.matchquery("age","40"));
        // searchsourcebuilder sourcebuilder = new searchsourcebuilder().query(boolquerybuilder);
        // searchrequest.source(sourcebuilder);
        // searchresponse searchresponse = esclient.search(searchrequest, requestoptions.default);
        // searchresponse.gethits().foreach(hit -> system.err.println(hit.getsourceasstring()));
        // 3-范围查询
        // searchrequest searchrequest = new searchrequest("user");
        // searchsourcebuilder sourcebuilder = new searchsourcebuilder();
        // rangequerybuilder rangequery = querybuilders.rangequery("age");
        // rangequery.gte("30");
        // sourcebuilder.query(rangequery);
        // searchrequest.source(sourcebuilder);
        // searchresponse searchresponse = esclient.search(searchrequest, requestoptions.default);
        // searchresponse.gethits().foreach(hit -> system.out.println(hit.getsourceasstring()));
        //4-模糊查询+高亮
        searchrequest searchrequest = new searchrequest("user");
        searchsourcebuilder sourcebuilder = new searchsourcebuilder();
        fuzzyquerybuilder fuzzyquery = querybuilders.fuzzyquery("name", "张三");
        sourcebuilder.query(fuzzyquery);
        highlightbuilder highlightbuilder = new highlightbuilder();
        highlightbuilder.pretags("<font color='red'>");
        highlightbuilder.posttags("</font>");
        highlightbuilder.field("name");
        sourcebuilder.highlighter(highlightbuilder);
        searchrequest.source(sourcebuilder);
        searchresponse searchresponse = esclient.search(searchrequest, requestoptions.default);
        searchresponse.gethits().foreach(system.out::println);
        // 5-聚合查询
        esclient.close();
    }
}

内容来自b站

https://www.bilibili.com/video/bv1hh411d7sb?p=62

以上就是springboot集成elasticsearch实现过程示例详解的详细内容,更多关于springboot框架集成es的资料请关注其它相关文章!