ES相关的增删改查操作示例
依赖:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
修改版本:

第一步:条件准备:首先是配置类:
@Configuration
public class EsConfig {
@Bean
public RestHighLevelClient client() {
return new RestHighLevelClient(RestClient.builder(HttpHost.create(EsConstant.ES_URL)));
}
}
第二步:将我们需要创建的索引,以及文档,和字段
比如:
public interface EsConstant {
//服务地址
String ES_URL = "http://192.168.138.100:9200";
//索引名称
String HOTEL_INDEX = "hotel";
//mapping映射
String HOTEL_MAPPING = "{\n" +
" \"mappings\": {\n" +
" \"properties\": {\n" +
" \"id\":{\n" +
" \"type\": \"keyword\"\n" +
" },\n" +
" \"name\":{\n" +
" \"type\":\"text\",\n" +
" \"analyzer\": \"ik_smart\",\n" +
" \"copy_to\": \"all\"\n" +
" },\n" +
" \"address\":{\n" +
" \"type\": \"text\",\n" +
" \"analyzer\": \"ik_smart\",\n" +
" \"copy_to\": \"all\"\n" +
" },\n" +
" }\n" +
" }\n" +
"}";
}
1.创建索引:(类似mysql创建数据表一样)
void contextLoads() throws IOException {
//执行创建索引对象,指定索引名
CreateIndexRequest createindexrequest = new CreateIndexRequest(EsConstant.HOTEL_INDEX);
//指定映射
createindexrequest.source(EsConstant.HOTEL_MAPPING, XContentType.JSON);
//创建索引
CreateIndexResponse response = client.indices().create(createindexrequest, RequestOptions.DEFAULT);
}
2.根据文档id查询文档内容:(类似mysql查询单个数据结果一样)
public void getDocTest() throws IOException {
//查询索引中的文档信息
GetRequest getRequest = new GetRequest(EsConstant.HOTEL_INDEX, "36934");
GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);
//将返回结果转成json字符串
String source = response.getSourceAsString();
//将json字符串转成查询对象
HotelDoc hotelDoc = JSONObject.parseObject(source, HotelDoc.class);
}
3.批量添加数据库中的内容到es索引
public void BanceAddTest() throws IOException {
//从数据库获取数据集合
List<Hotel> hotelList = hotelService.list();
ArrayList<HotelDoc> list = new ArrayList<>();
for (Hotel hotel : hotelList) {
HotelDoc hotelDoc = new HotelDoc(hotel);
list.add(hotelDoc);
}
BulkRequest bulkrequest = new BulkRequest();
for (HotelDoc hotelDoc : list) {
//创建请求对象并添加数据
IndexRequest source = new IndexRequest(EsConstant.HOTEL_INDEX)
//获取文档id并转成字符串
.id(hotelDoc.getId().toString())
//将对象转成json字符串
.source(JSONObject.toJSONString(hotelDoc), XContentType.JSON);
//添加文档对象
bulkrequest.add(source);
}
//增加文档到索引中
BulkResponse bulk = client.bulk(bulkrequest, RequestOptions.DEFAULT);
}
以上就是关于索引常用的api示例.

浙公网安备 33010602011771号