1springboot簡單實用java
--依賴node
<!--es的依賴-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
</dependency>spring
--yml的配置springboot
spring:
data:
elasticsearch:
cluster-name: elasticsearch
cluster-nodes: 127.0.0.1:9300 #java的客戶端要用9300 服務器地址 配置es的地址
服務器
--須要建立一個文檔映射app
/**
* 文檔映射:
*
* index type
*/
@Document(indexName = "xxx",type = "emp")
public class Employee {
@Id
private Long id;
@Field(type = FieldType.Keyword)
private String name;
// intro使用text類型進行映射;analyzer:索引建立時使用的分詞器
//searchAnalyzer:搜索分詞器:搜索該字段的值時,傳入的查詢內容的分詞器
@Field(type = FieldType.Text,analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")
private String intro;
private Integer age;elasticsearch
--啓動類測試
@SpringBootApplication
public class EsApplication {
public static void main(String[] args) {
SpringApplication.run(EsApplication.class);
}
}spa
--測試索引
--首先進行環境的初始化
@RunWith(SpringRunner.class)
@SpringBootTest(classes = EsApplication.class)
public class EsTest {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Test
public void testInit()throws Exception{
//建立索引 作映射
elasticsearchTemplate.createIndex(Employee.class);
//作映射
elasticsearchTemplate.putMapping(Employee.class);
}
}
--crud的操做
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Autowired
private EsRepository esRepository;
@Test
public void testInit() throws Exception {
//建立索引 作映射
elasticsearchTemplate.createIndex(Employee.class);
//作映射
elasticsearchTemplate.putMapping(Employee.class);
}
@Test
public void testAdd() throws Exception {
esRepository.save(new Employee(1L, "111", "I 1", 919));
}等等
2.es的項目實戰
--Es的服務單獨封裝爲一個服務--給內部調用的:feign
--依賴
<!--es的依賴-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
</dependency>
--定義接口
@FeignClient(value = "xxx-PRIVODER",fallbackFactory = ProductEsClientFactory.class) //表示對哪個服務進行處理
@RequestMapping("/xxx/es")
public interface ProductEsClient {
//添加一個
@RequestMapping(value = "/productdoc", method = RequestMethod.POST)
AjaxResult addOne(@RequestBody ProductDoc productDoc);
//批量添加
@RequestMapping(value = "/productdocs", method = RequestMethod.POST)
AjaxResult addBatch(@RequestBody List<ProductDoc> productDocList);
//刪除一個
@RequestMapping(value = "/productdoc/{id}", method = RequestMethod.DELETE)
AjaxResult deleteOne(@PathVariable("id") Long id );
//批量刪除
@RequestMapping(value = "/productdocs", method = RequestMethod.DELETE)
AjaxResult deleteBatch(@RequestBody List<Long> ids );
//查詢一個
@RequestMapping(value = "/productdoc/{id}", method = RequestMethod.GET)
AjaxResult findOne(@PathVariable("id") Long id );
}
--配置yml文件
xxx-service:增長配置文件:
spring:
application:
name: xxx-PRIVODER
data:
elasticsearch:
cluster-name: elasticsearch
cluster-nodes: 127.0.0.1:9300
--定義Repository接口
public interface ProductRepository extends ElasticsearchRepository<ProductDoc,Long>{
}
--定義service/controller-->按照ProductEsClient來寫
--最後在消費者層寫本身的業務邏輯。。。。。。