pom.xml中配置使用的依赖
<spring-boot.version>2.3.4.RELEASE</spring-boot.version>
<spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
elasticsearch依赖
<!-- 使用ElasticsearchRestTemplate模板依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
在application.xml中配置文件
#项目名
spring:
application:
name: jq-search
#连接es
elasticsearch:
rest:
uris: http://192.168.230.134:9200
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#端口号
server:
port: 5053
#连接服务端
eureka:
client:
service-url:
defaultZone: http://localhost:5051/eureka
创建controller类进行简单测试
package com.jq.controller;
import com.jq.model.SerchModel;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.stream.Stream;
@RestController
@CrossOrigin
@RequestMapping("search")
public class SearchController {
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
@GetMapping()
public Object getSerch(String name){
//构建分页
Pageable pageable= PageRequest.of(0,999);
NativeSearchQueryBuilder builder=new NativeSearchQueryBuilder();
NativeSearchQuery query=builder.withQuery(QueryBuilders.queryStringQuery(name))
.withPageable(pageable)
.build();
SearchHits<SerchModel> search = elasticsearchRestTemplate.search(query, SerchModel.class);
Stream<SearchHit<SerchModel>> searchHitStream = search.get();
return searchHitStream;
}
}