springboot全文检索ElasticSearch

以前学习过solr luncene

他们两个关系 :solr是原生库,luncene是原生库包装的一个工具类,使用luncene的时候一般根据业务需求需要自己配置filed,每个field可以存的数据类型是不同的,默认有提供一些field给我们使用,操作配置过于繁琐

elasticsearch是对luncene的封装,让操作全文检索更为方便,今天看完雷丰阳的springboot - elasticsearch视频后在网上看到笔记在此做一个记录,方便以后查阅

https://www.cnblogs.com/h--d/p/12498224.html

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Spring Boot 中进行全文检索可以使用 Elasticsearch 这个搜索引擎,Elasticsearch 是一个基于 Lucene 的搜索引擎,它提供了一个分布式、多租户的全文搜索引擎。Elasticsearch 以文档为中心,每个文档都是一个 JSON 对象,可以通过 RESTful API 进行操作。 下面是使用 Elasticsearch 实现全文检索的步骤: 1. 添加 Elasticsearch 依赖 在 pom.xml 中添加 Elasticsearch 的依赖: ```xml <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.12.1</version> </dependency> ``` 2. 配置 Elasticsearch 客户端 在 application.properties 文件中添加 Elasticsearch 客户端的配置: ```properties spring.elasticsearch.rest.uris=http://localhost:9200 ``` 3. 创建索引 创建一个索引,可以理解为创建一个数据库表,在其中添加一些文档,这些文档就是我们要检索的对象。 ```java @Service public class BookService { @Autowired private RestHighLevelClient client; public void createIndex(String index) throws IOException { CreateIndexRequest request = new CreateIndexRequest(index); client.indices().create(request, RequestOptions.DEFAULT); } public void addDocument(String index, Book book) throws IOException { IndexRequest request = new IndexRequest(index); request.id(book.getId().toString()); request.source(new ObjectMapper().writeValueAsString(book), XContentType.JSON); client.index(request, RequestOptions.DEFAULT); } } ``` 4. 搜索文档 搜索文档需要使用 Elasticsearch 的查询 API,可以根据关键词、字段、范围等条件进行查询。 ```java @Service public class BookService { @Autowired private RestHighLevelClient client; public List<Book> search(String index, String keyword) throws IOException { SearchRequest request = new SearchRequest(index); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.matchQuery("title", keyword)); request.source(sourceBuilder); SearchResponse response = client.search(request, RequestOptions.DEFAULT); return Arrays.stream(response.getHits().getHits()) .map(hit -> { try { return new ObjectMapper().readValue(hit.getSourceAsString(), Book.class); } catch (JsonProcessingException e) { e.printStackTrace(); } return null; }) .collect(Collectors.toList()); } } ``` 以上就是使用 Elasticsearch 实现全文检索的基本步骤,当然还有很多高级的用法,例如聚合、分页等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值