新建spring boot项目:
5.2 配置org.springframework.boot spring-boot-starter-weborg.springframework.boot spring-boot-starter-data-elasticsearchorg.projectlombok lombok
配置文件:
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() { SearchHitssearch = elasticsearchOperations.search(Query.findAll(), Student.class, IndexCoordinates.of("student")); for (SearchHit hit : search) { System.out.println(hit.getContent()); } } @Test void findBySome(){ Criteria criteria = new Criteria("name").is("zs"); Query query = new CriteriaQuery(criteria); SearchHits search = elasticsearchOperations.search(query, Student.class, IndexCoordinates.of("student")); for (SearchHit hit : search) { System.out.println(hit.getContent()); } } @Test void findBySome2(){ Criteria contains = new Criteria("name").contains("s"); Query query = new CriteriaQuery(contains); SearchHits search = elasticsearchOperations.search(query, Student.class, IndexCoordinates.of("student")); for (SearchHit hit : search) { System.out.println(hit.getContent()); } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)