玩转Elasticsearch—Spring Data整合ES7.16.3

玩转Elasticsearch—Spring Data整合ES7.16.3,第1张

玩转Elasticsearch—Spring Data整合ES7.16.3 5.1 pom依赖

新建spring boot项目:


    org.springframework.boot
    spring-boot-starter-web



    org.springframework.boot
    spring-boot-starter-data-elasticsearch


    org.projectlombok
    lombok

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 search = 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());
        }
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5715257.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存