用ElasticsearchRestTemplate来操作Elasticsearch增删改查等功能

写本文的目的就是分享一下我自己常用的基本方法使用,也方便我自己以后来看看~

截至今日,spring官方更新到 Spring Data Elasticsearch 4.4,也就是支持Elasticsearch 7.17.4以下的版本。本人使用的ES版本是7.15.1,集群部署在linux Centos Steam上,是可以运行的,没有问题的!

那么话不多说,开始!

项目构建!

按照spring boot构建流程正常进行就可以。直到在要你选择依赖时,直接查找elastic,然后勾选就行了

创建好后,依赖长这样~

开始操作!

1.基本准备!

1.1application.properties配置

配置你的连接,我是在linux上部署的elasticsearch

可以配置单体的连接

spring.elasticsearch.uris=http://192.168.10.130:9200

也可以配置集群的,之间用逗号连接就行!

spring.elasticsearch.uris=http://192.168.10.130:9200, http://192.168.10.131:9200, http://192.168.10.132:9200

如果你的es有设置账号密码的话,还要配置他们

spring.elasticsearch.password=spring.elasticsearch.username=

还要好多高级配置并不是刚需,这里就不配置了

1.2自定义mapping

自定义索引index的mapping,也就是我们需要直接自定义一个实体类!

要注意:

@Data@AllArgsConstructor@NoArgsConstructor@Document(indexName = "book")public class Book {    @Id    private String id;    @Field(type = FieldType.Keyword)    private String title;    @Field(type = FieldType.Integer)    private Integer price;    @Field(type = FieldType.Text, analyzer = "ik_max_word")    private String info;}

2.索引index的操作

2.1创建索引

可以创建无mapping的;也可以创建有mapping的,就是根据刚刚创建的实体类Book来的~

//    TODO 索引的创建    @Test    void createIndex() {//        使用IndexOperations操作        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(Book.class);//        创建索引,无mapping        boolean createResult = indexOperations.create();        System.out.println("索引创建" + createResult);//        自定义mapping//        根据类中注解自动产生mapping        Document mapping = indexOperations.createMapping(Book.class);        boolean mappingResult = indexOperations.putMapping(mapping);        System.out.println("mapping创建" + mappingResult);    }

看看是否创建成功~

@Test    void YO(){        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(Book.class);        Map mapping = indexOperations.getMapping();        System.out.println("Book mapping:" + mapping);    }

出现以下,就是成功辣:

Book mapping:{properties={price={type=integer}, _class={index=false, type=keyword, doc_values=false}, title={type=keyword}, info={analyzer=ik_max_word, type=text}}}

2.2删除索引

删索引前,可以判断一下存不存在~

//    TODO 索引的删除    @Test    void delIndex(){        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(Book.class);//        判断存不存在索引        if (indexOperations.exists()){            indexOperations.delete();            System.out.println("删除成功!");        }        else {            System.out.println("没有此索引,删除失败!");        }    }

3.文档document的操作

3.1添加文档

可以指定id,也可以不指定,不指定ES会自己帮你生成

@Test//    TODO 添加文档 Document    void addDoc(){        Book book = new Book(null, "秃头修炼手册", 998, "你,渴望力量吗?");        Book save = elasticsearchRestTemplate.save(book);        System.out.println(save);    }

效果如下:

Book(id=RERVbIIBMBIlA2IGq_0r, title=秃头修炼手册, price=998, info=你,渴望力量吗?)

3.2删除文档

根据id删除文档

@Test//    TODO 删除文档 Document    void delDoc(){        String delete = elasticsearchRestTemplate.delete("RURebIIBMBIlA2IGNP3r", Book.class);        System.out.println(delete);    }

3.3修改文档

第一种是全量替换的更新文档,和上面添加文档save是一样的,这边就不多说了

还有一种是局部更新,就像下面一样,只更新价格

@Test//    TODO 局部修改/新增    void updateDoc_aim(){        Document document = Document.create();        document.put("price", 98);//        UpdateQuery.builder绑的是id        elasticsearchRestTemplate.update(UpdateQuery.builder("1").withDocument(document).build(), IndexCoordinates.of("book"));    }

3.4查询文档

查询有好多种查询,可以按主键查、模糊查询、查询全部、准确查询、范围查询等等

@Test//    TODO 查询    void search(){//        主键查询        Book book = elasticsearchRestTemplate.get("1", Book.class);        System.out.println("主键查询:" + book);//        模糊查询        NativeSearchQuery query = new NativeSearchQuery(QueryBuilders.queryStringQuery("98"));        for (SearchHit search : elasticsearchRestTemplate.search(query, Book.class)) {            System.out.println("模糊查询:" + search.getContent());        }//        matchAll 查询全部        NativeSearchQuery query1 = new NativeSearchQuery(QueryBuilders.matchAllQuery());        for (SearchHit search : elasticsearchRestTemplate.search(query1, Book.class)) {            System.out.println("查询全部:" + search.getContent());        }//        精确查询        NativeSearchQuery query2 = new NativeSearchQuery(QueryBuilders.matchQuery("title", "夏提雅的笔记"));        for (SearchHit search : elasticsearchRestTemplate.search(query2, Book.class)) {            System.out.println("精确查询:" + search.getContent());        }//        范围查询        NativeSearchQuery query3 = new NativeSearchQuery(QueryBuilders.rangeQuery("price").gte(900).lte(9000));        for (SearchHit search : elasticsearchRestTemplate.search(query3, Book.class)) {            System.out.println("范围查询:" + search.getContent());        }    }

可以在kibana中查看我book的文档,对照查询结果,如下

主键查询:Book(id=1, title=秃头修炼手册, price=98, info=你,渴望力量吗?)

模糊查询:Book(id=1, title=秃头修炼手册, price=98, info=你,渴望力量吗?)

模糊查询:Book(id=R0RtbIIBMBIlA2IGkf1H, title=秃头修炼手册, price=98, info=你,渴望力量吗?)

查询全部:Book(id=RkRebIIBMBIlA2IGRf0l, title=秃头修炼手册, price=998, info=你,渴望力量吗?)

查询全部:Book(id=1, title=秃头修炼手册, price=98, info=你,渴望力量吗?)

查询全部:Book(id=R0RtbIIBMBIlA2IGkf1H, title=秃头修炼手册, price=98, info=你,渴望力量吗?)

查询全部:Book(id=SERtbIIBMBIlA2IG5v0c, title=秃头修炼手册, price=99998, info=你,渴望力量吗?)

查询全部:Book(id=SURxbIIBMBIlA2IGfP3P, title=夏提雅的笔记, price=998, info=安兹大人好帅!)

精确查询:Book(id=SURxbIIBMBIlA2IGfP3P, title=夏提雅的笔记, price=998, info=安兹大人好帅!)

范围查询:Book(id=RkRebIIBMBIlA2IGRf0l, title=秃头修炼手册, price=998, info=你,渴望力量吗?)

范围查询:Book(id=SURxbIIBMBIlA2IGfP3P, title=夏提雅的笔记, price=998, info=安兹大人好帅!)

3.5分页查询

分页功能也是很好用的,例子如下

//    TODO 分页与排序    @Test    void sortPage(){        NativeSearchQuery query = new NativeSearchQuery(QueryBuilders.matchAllQuery());//        查看第0页,每页2条数据,按价格递增排序        query.setPageable(PageRequest.of(0, 2, Sort.by(Sort.Direction.ASC, "price")));        for (SearchHit search : elasticsearchRestTemplate.search(query, Book.class)) {            System.out.println(search.getContent());        }    }}

结果如下:

Book(id=1, title=秃头修炼手册, price=98, info=你,渴望力量吗?)

Book(id=R0RtbIIBMBIlA2IGkf1H, title=秃头修炼手册, price=98, info=你,渴望力量吗?)

结尾

分享一下,拥抱开源

啦啦啦

原文链接:https://blog.csdn.net/bb1272196672/article/details/126173335

展开阅读全文

页面更新:2024-03-01

标签:操作   分词   秃头   注解   索引   模糊   力量   手册   文档   笔记

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号

Top