springboot之elasticsearch的接入
一,项目结构
二,引用包
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-elasticsearch</artifactId> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.6.2</version> </dependency>
三,代码如下
EsApplication
package com.nl; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * spring-data-elasticsearch * elasticsearch-rest-high-level-client */ @SpringBootApplication public class EsApplication { public static void main(String[] args) { System.out.println("test"); SpringApplication.run(EsApplication.class, args); } }
发生的
IEsCardService
package com.nl.Service; import com.nl.model.EsTestPo; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.stereotype.Repository; import java.util.List; /** * 接口使用关键字生成实现,特定语法 * 文档地址:https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.query-methods.criterions */ @Repository public interface IEsCardService extends ElasticsearchRepository<EsTestPo, String> { Page<EsTestPo> queryFirstById(String id, Pageable pageable); List<EsTestPo> findByIdAndName(String id,String name); }
EsTestPo
package com.nl.model; import org.springframework.data.elasticsearch.annotations.Document; @Document(indexName = "EsTestPo", shards = 1, replicas = 0) public class EsTestPo { public Long id; public Long name; }
EsTest
import com.nl.EsApplication; import com.nl.Service.IEsCardService; import com.nl.model.EsTestPo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest(classes = EsApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class EsTest { @Resource private IEsCardService iEsCardService; @Test public void EsTest() { List<EsTestPo> es = iEsCardService.findByIdAndName("1735308454",""); System.out.println("Test"); } }
application.yml
spring: profiles: active: dev elasticsearch: rest: password: 123456 username: elastic uris: http://localhost:9200
四。特定语法的使用参考
文档地址:https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.query-methods.criterions