1. 创建索引库:
//创建索引库
@Test
void createHotelIndex() throws IOException {
//1.创建Request对象
CreateIndexRequest request = new CreateIndexRequest("hotel");
//2.准备请求的参数:DSL语句
request.source(MAPPING_TEMPLATE, XContentType.JSON);
//3.发送请求
client.indices().create(request,RequestOptions.DEFAULT);
}
public static final String MAPPING_TEMPLATE = "{\n" +
" "mappings": {\n" +
" "properties": {\n" +
" "id":{\n" +
" "type":"keyword"\n" +
" },\n" +
" "name":{\n" +
" "type":"text",\n" +
" "analyzer": "ik_max_word",\n" +
" "copy_to": "all"\n" +
" },\n" +
" "address":{\n" +
" "type":"keyword",\n" +
" "index":"false"\n" +
" },\n" +
" "price":{\n" +
" "type":"integer"\n" +
" },\n" +
" "score":{\n" +
" "type":"integer"\n" +
" },\n" +
" "brand":{\n" +
" "type":"keyword",\n" +
" "copy_to": "all"\n" +
" },\n" +
" "city":{\n" +
" "type":"keyword"\n" +
" },\n" +
" "starName":{\n" +
" "type":"keyword"\n" +
" },\n" +
" "business":{\n" +
" "type":"keyword",\n" +
" "copy_to": "all"\n" +
" },\n" +
" "location":{\n" +
" "type":"geo_point"\n" +
" },\n" +
" "pic":{\n" +
" "type":"keyword",\n" +
" "index":false\n" +
" },\n" +
" "all":{\n" +
" "type":"text",\n" +
" "analyzer": "ik_max_word"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
编辑
2. 删除索引库:
//删除索引库
@Test
void textDeleteHotelIndex() throws IOException {
//1.创建Request对象
DeleteIndexRequest request = new DeleteIndexRequest("hotel");
//2.发送请求
client.indices().delete(request,RequestOptions.DEFAULT);
}
3. 旁段是否存在索引库:
//判断是否存在索引库
@Test
void textExistsHotelIndex() throws IOException {
//1.创建Request对象
GetIndexRequest request = new GetIndexRequest("hotel");
//2.发送请求
boolean exists = client.indices().exists(request,RequestOptions.DEFAULT);
System.out.println(exists ? "索引库已经存在!" : "索引库不存在!");
}
4. 修改文档
//修改文档
@Test
void testUpdateDocument() throws IOException {
//1.准备Request
UpdateRequest request = new UpdateRequest("hotel","61083");
//2.准备请求参数
request.doc(
"price","952",
"starName","四钻"
);
//3.发送请求
client.update(request,RequestOptions.DEFAULT);
}
5. 查询文档
//根据id查询
@Test
void testAddDocumentById() throws IOException {
//1.准备好request
GetRequest request = new GetRequest("hotel","61083");
//2.发送请求 ,得到响应
GetResponse response = client.get(request,RequestOptions.DEFAULT);
//3.解析响应结果
String json = response.getSourceAsString();
HotelDoc hotelDoc= JSON.parseObject(json,HotelDoc.class);
System.out.println(hotelDoc);
}
6. 批量添加文档
//批量添加
@Test
void testBulkRequest() throws IOException {
//批量查询酒店的数量
List<Hotel> hotels = new hotelService.list();
for(Hotel hotel : hotels){
HotelDoc hotelDoc = new HotelDoc(hotel);
}
//1.创建Request
BulkRequest request = new BulkRequest();
//2.准备参数,添加多个新增的Request
for(Hotel hotel : hotels){
//转换为文档类型的HotelDoc
HotelDoc hotelDoc = new HotelDoc(hotel);
//创建新增文档的Request对象
request.add(new IndexRequest("hotel")
.id(hotelDoc.getId().toString())
.source(JSON.toJSONString(hotelDoc),XContentType.JSON));
}
//3.发送请求
client.bulk(request,RequestOptions.DEFAULT);
}