1. 準備工作
需要提前安裝好Elasticsearch,訪問地址:http://127.0.0.1:9200/ 得到以下結果,得到cluster_name,下面配置使用。
{
"name" : "O8GslS3",
"cluster_name" : "docker-cluster",
"cluster_uuid" : "pviTqfXtR3GtnxF-Po-_aA",
"version" : {
"number" : "6.5.0",
......
},
"tagline" : "You Know, for Search"
}
2. 使用Maven創建SpringBoot工程
配置Maven的pom.xml文件
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
</dependencies>
注意:spring-boot-starter-data-elasticsearch包,引用的是spring-data-elasticsearch包,而spring-data-elasticsearch包的版本與elasticsearch服務版本是有兼容性問題的。
目前并不支持elasticsearch7.x,參考:https://github.com/spring-projects/spring-data-elasticsearch

配置application.yml文件
spring:
data:
elasticsearch:
cluster-name: docker-cluster
cluster-nodes: 127.0.0.1:9300
repositories:
enabled: true
3. 代碼
實體類。使用@Document注解,參數indexName是索引名稱,type是type名稱。
// 聲明索引名稱,type名稱@Document(indexName = "houseindex", type = "house")
public class HouseIndexTemplate {
@Id
private Long id;
private String name; ......
}
訪問接口。使用@Repository注解,并繼承ElasticsearchRepository接口,就可以直接訪問的。
有兩個參數:1.返回的對象,2.ID參數數據類型
@Repository
public interface HouseRepository extends ElasticsearchRepository<HouseIndexTemplate, Long> {
}
測試用例
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class UserServiceTest {
@Autowired
private HouseRepository houseRepository;
@Test
public void selectUser(){ HouseIndexTemplate template = new HouseIndexTemplate(); template.setId(1); template.setName("Tom");
houseRepository.save(template);
}
}
4. 異常解釋
問題1: NoNodeAvailableException[None of the configured nodes are available: [{#transport#-1}{IVH9QII0QrOU9GkXdsJPiA}{127.0.0.1}{127.0.0.1:9300}]]
原因:這是說配置的節點不可用,原因答題有3種可能:(1)IP地址或端口填寫有誤;(2)cluster_name填寫有誤;(3)Elasticsearch服務已關閉
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。