0


SpringBoot-spring-data-elasticsearch7.12.0

maven

注意springboot的版本一定要和elasticsearch和spring-boot-starter-data-elasticsearch的版本匹配,不然就会出现问题

<properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.5.1</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>7.12.0 </version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-to-slf4j</artifactId><version>2.9.1</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.24</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-simple</artifactId><version>1.7.21</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.12</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>

application.yml

server:port:9091spring:elasticsearch:rest:uris: 106.12.174.220:9200connection-timeout: 1s
      read-timeout: 30s

演示

Article

packagecom.es.entity;importorg.springframework.data.annotation.Id;importorg.springframework.data.elasticsearch.annotations.Document;importorg.springframework.data.elasticsearch.annotations.Field;importorg.springframework.data.elasticsearch.annotations.FieldType;//@Document 文档对象 (索引信息、文档类型 )@Document(indexName="blog3")publicclassArticle{//@Id 文档主键 唯一标识@Id//@Field 每个文档的字段配置(类型、是否分词、是否存储、分词器 )@Field(store=true, index =false,type =FieldType.Integer)privateInteger id;@Field(index=true,analyzer="ik_smart",store=true,searchAnalyzer="ik_smart",type =FieldType.Text)privateString title;@Field(index=true,analyzer="ik_smart",store=true,searchAnalyzer="ik_smart",type =FieldType.Text)privateString content;@Field(index=true,store=true,type =FieldType.Double)privateDouble price;publicDoublegetPrice(){return price;}publicvoidsetPrice(Double price){this.price = price;}publicIntegergetId(){return id;}publicvoidsetId(Integer id){this.id = id;}publicStringgetTitle(){return title;}publicvoidsetTitle(String title){this.title = title;}publicStringgetContent(){return content;}publicvoidsetContent(String content){this.content = content;}@OverridepublicStringtoString(){return"Article{"+"id="+ id +", title='"+ title +'\''+", content='"+ content +'\''+", price="+ price +'}';}}

ArticleRepository

packagecom.es.dao;importcom.es.entity.Article;importorg.springframework.data.elasticsearch.annotations.Highlight;importorg.springframework.data.elasticsearch.annotations.HighlightField;importorg.springframework.data.elasticsearch.annotations.HighlightParameters;importorg.springframework.data.elasticsearch.core.SearchHit;importorg.springframework.data.elasticsearch.repository.ElasticsearchRepository;importorg.springframework.stereotype.Repository;importjava.util.List;@RepositorypublicinterfaceArticleRepositoryextendsElasticsearchRepository<Article,Integer>{/**
     * 查询内容标题查询
     * @param title 标题
     * @param content 内容
     * @return 返回关键字高亮的结果集
     */@Highlight(
            fields ={@HighlightField(name ="title"),@HighlightField(name ="content")},
            parameters =@HighlightParameters(preTags ={"<span style='color:red'>"}, postTags ={"</span>"}, numberOfFragments =0))List<SearchHit<Article>>findByTitleOrContent(String title,String content);}

ArticleService

packagecom.es.service;importcom.es.entity.Article;importorg.springframework.data.elasticsearch.core.SearchHit;importjava.util.List;publicinterfaceArticleService{//保存和修改voidsave(Article article);//查询idArticlefindById(Integer id);//删除指定ID数据voiddeleteById(Integer id);longcount();booleanexistsById(Integer id);List<SearchHit<Article>>findByTitleOrContent(String title,String content);}

ArticleServiceImpl

packagecom.es.service.impl;importcom.es.dao.ArticleRepository;importcom.es.entity.Article;importcom.es.service.ArticleService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.data.elasticsearch.core.SearchHit;importorg.springframework.stereotype.Service;importjava.util.List;@ServicepublicclassArticleServiceImplimplementsArticleService{@AutowiredprivateArticleRepository articleRepository;@Overridepublicvoidsave(Article article){
       articleRepository.save(article);}@OverridepublicArticlefindById(Integer id){Article article = articleRepository.findById(id).orElse(newArticle());return  article;}@OverridepublicvoiddeleteById(Integer id){
        articleRepository.deleteById(id);}@Overridepubliclongcount(){return articleRepository.count();}@OverridepublicbooleanexistsById(Integer id){return articleRepository.existsById(id);}@OverridepublicList<SearchHit<Article>>findByTitleOrContent(String title,String content){return articleRepository.findByTitleOrContent(title,content);}}

ESApplication

packagecom.es;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublicclassESApplication{publicstaticvoidmain(String[] args){SpringApplication.run(ESApplication.class,args);}}

SpringDataESTest

packagecom.es;importcom.es.entity.Article;importcom.es.service.ArticleService;importorg.elasticsearch.client.transport.TransportClient;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;importorg.springframework.data.elasticsearch.core.ElasticsearchTemplate;importorg.springframework.data.elasticsearch.core.SearchHit;importorg.springframework.test.context.junit4.SpringRunner;importjavax.annotation.Resource;importjava.util.List;@RunWith(SpringRunner.class)@SpringBootTest(classes =ESApplication.class, webEnvironment =SpringBootTest.WebEnvironment.DEFINED_PORT)publicclassSpringDataESTest{@AutowiredprivateArticleService articleService;@AutowiredprivateElasticsearchRestTemplate elasticsearchRestTemplate;/**创建索引和映射*/@org.junit.TestpublicvoidcreateIndex(){//        elasticsearchTemplate.createIndex(Article.class);//        elasticsearchTemplate.putMapping(Article.class);}/**添加文档或者修改文档(以id为准)*/@TestpublicvoidsaveArticle(){Article article =newArticle();
        article.setId(102);
        article.setTitle("xxxxxxSpringData ElasticSearch-------");
        article.setContent("Spring Data ElasticSearch 基于 spring data API 简化 elasticSearch操作,将原始操作elasticSearch的客户端API 进行封装 \n"+"    Spring Data为Elasticsearch Elasticsearch项目提供集成搜索引擎");
        articleService.save(article);}@TestpublicvoidfindById(){Article byId = articleService.findById(100);System.out.println(byId);}@TestpublicvoiddeleteById(){
       articleService.deleteById(100);}@Testpublicvoidcount(){long count = articleService.count();System.out.println(count);}@TestpublicvoidexistsById(){boolean b = articleService.existsById(102);System.out.println(b);}@TestpublicvoidfindByTitleOrContent(){List<SearchHit<Article>> byTitleOrContent = articleService.findByTitleOrContent("xxxxxxSpringData","elasticSearch");for(SearchHit<Article> articleSearchHit : byTitleOrContent){List<String> title = articleSearchHit.getHighlightField("title");System.out.println(title);List<String> content = articleSearchHit.getHighlightField("content");System.out.println(content);}}}

自定义查询方式

关键字解释方法and根据Field1和Field2获得数据findByTitleAndContent(String title,String content);or根据Field1或Field2获得数据findByTitleOrContent(String title,String content);is根据Field获得数据findByTitle(String title);not根据Field获得相反数据findByTitleNot(String title)between获得指定范围的数据findByPriceBetween(double price1, double price2);lessThanEqual获得小于等于指定值的数据findByPriceLessThan(double price);GreaterThanEqual获得大于等于指定值的数据findByPriceGreaterThan(double price);BeforefindByPriceBeforeAfterfindByPriceAfterLike比较相识的数据findByNameLikeStartingWith以xx开头的 数据findByNameStartingWith(String Name);EndingWith以xx结尾的 数据findByNameEndingWith(String Name);Contains/Containing包含的 数据findByNameContaining(String Name);In多 值匹配findByNameIn(Collection<String>names)NotIn多 值 不匹配findByNameNotIn(Collection<String>names)OrderBy排序 后的数据findByxxxxxOrderByNameDesc(String xxx );

比如: findByTitleAndContent 如果你的表中没有title字段和content那么就无效这个方法
列: List

findByTitleAndContent(String title,String content);

获得指定范围的数据: 方法 findByPriceBetween
列: List

findByPriceBetween(double price1, double price2);

获得小于等于指定值的数据
列: List

findByPriceLessThan(double price);

在这里插入图片描述
点赞 -收藏-关注-便于以后复习和收到最新内容有其他问题在评论区讨论-或者私信我-收到会在第一时间回复在本博客学习的技术不得以任何方式直接或者间接的从事违反中华人民共和国法律,内容仅供学习、交流与参考 免责声明:本文部分素材来源于网络,版权归原创者所有,如存在文章/图片/音视频等使用不当的情况,请随时私信联系我、以迅速采取适当措施,避免给双方造成不必要的经济损失。感谢,配合,希望我的努力对你有帮助^_^


本文转载自: https://blog.csdn.net/weixin_45203607/article/details/126132253
版权归原作者 胡安民 所有, 如有侵权,请联系我们删除。

“SpringBoot-spring-data-elasticsearch7.12.0”的评论:

还没有评论