@Document(indexName = “stu”, shards = 3, replicas = 0)
public class Stu {
@Id
private Long stuId;
@Field(store = true, analyzer = “ik_max_word”, type = FieldType.Text)
private String name;
@Field(store = true, type = FieldType.Integer)
private Integer age;
@Field
private Float money;
@Field
private boolean isMarried;
// getter、setter、toString() 省略
}
- @Document定义在Elasticsearch中索引信息
- @Id定义了Elasticsearch的_id
- @Field定义字段类型等信息
- …更多注解请参照官方文档…
2. 创建测试类 ESTest.java
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class ESTest {
@Autowired
private ElasticsearchRestTemplate esTemplate;
…
}
这里使用 ElasticsearchRestTemplate 方式执行增删改查
2.1 创建索引
@Test
public void createIndex(){
esTemplate.indexOps(Stu.class).create();
}
2.2 删除索引
@Test
public void deleteIndex() {
esTemplate.indexOps(Stu.class).delete();
}
2.3 判断索引是否存在
@Test
public void existIndex() {
boolean isExist = esTemplate.indexOps(Stu.class).exists();
System.out.println(isExist);
}
2.4 新增文档数据
@Test
public void addDoc() {
Stu stu0 = new Stu(10010L, “didiok”, 18, 100.5f, true);
esTemplate.save(stu0);
Stu stu1 = new Stu(10011L, “Rede”, 20, 88.5f, true);
Stu stu2 = new Stu(10012L, “放下”, 22, 108.5f, false);
List stuList = new ArrayList<>();
stuList.add(stu1);
stuList.add(stu2);
esTemplate.save(stuList);
}
2.5 根据文档id删除数据
@Test
public void deleteDoc(){
esTemplate.delete(“10010”, Stu.class);
}
2.6 查询文档数据
@Test
public void getDoc(){
System.out.println(esTemplate.get(“10011”, Stu.class));
}
2.7 修改文档数据
@Test
public void updateDoc(){
Map<String, Object> stuMap = new HashMap<>();
stuMap.put(“name”, “秦王嬴政”);
stuMap.put(“age”, 2000);
Document doc = Document.from(stuMap);
UpdateQuery updateQuery = UpdateQuery.builder(“10011”)
.withDocument(doc)
.build();
IndexCoordinates indexCoordinate = IndexCoordinates.of(“stu”);
esTemplate.update(updateQuery, indexCoordinate);
}
2.8 搜索数据
/**
- 搜索数据
*/
@Test
public void searchStu(){
Pageable pageable = PageRequest.of(0, 10);
SortBuil