5.1 pom依赖
新建spring boot项目:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 依赖web starter--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> 复制代码
5.2 配置
配置文件:
es: address: 127.0.0.1 port: 9200 复制代码
配置类:
@Configuration public class ElasticsearchConfig extends AbstractElasticsearchConfiguration { @Value("${es.address}") private String address; @Value("${es.port}") private Integer port; @Override @Bean public RestHighLevelClient elasticsearchClient() { final String ES_URL = address + ":" + port; final ClientConfiguration clientConfiguration = ClientConfiguration.builder() .connectedTo(ES_URL) .build(); return RestClients.create(clientConfiguration).rest(); } } 复制代码
5.3 编码测试
@SpringBootTest class SpEsApplicationTests { @Autowired private ElasticsearchOperations elasticsearchOperations; @Test void save() { Student student = new Student(3L, "ww", 13, "上海"); IndexQuery indexQuery = new IndexQueryBuilder() .withId(student.getId().toString()) .withObject(student) .build(); String str = elasticsearchOperations.index(indexQuery, IndexCoordinates.of("student")); System.out.println(str); } @Test void findById() { Student student = elasticsearchOperations.get("1", Student.class, IndexCoordinates.of("student")); System.out.println(student); } @Test void findAll() { SearchHits<Student> search = elasticsearchOperations.search(Query.findAll(), Student.class, IndexCoordinates.of("student")); for (SearchHit<Student> hit : search) { System.out.println(hit.getContent()); } } @Test void findBySome(){ Criteria criteria = new Criteria("name").is("zs"); Query query = new CriteriaQuery(criteria); SearchHits<Student> search = elasticsearchOperations.search(query, Student.class, IndexCoordinates.of("student")); for (SearchHit<Student> hit : search) { System.out.println(hit.getContent()); } } @Test void findBySome2(){ Criteria contains = new Criteria("name").contains("s"); Query query = new CriteriaQuery(contains); SearchHits<Student> search = elasticsearchOperations.search(query, Student.class, IndexCoordinates.of("student")); for (SearchHit<Student> hit : search) { System.out.println(hit.getContent()); } } }