:::tips 如果要将数据库表的数据查询出来封装到ElasticSearch中的索引库中,就需要先去查询数据库,如果数据库的结构、字段和索引库中的结构、字段不一致,就需要创建索引库对应的实体类,用来与ElasticSearch中的索引库进行映射,并设置这个实体类的构造参数,用于将数据表对应的实体类转化为索引库对应的实体类 :::

    1. @SpringBootTest
    2. public class MyTest{
    3. //注入RestHighLevelClient对象
    4. @Autowired
    5. private RestHighLevelClient restHighLevelClient;
    6. @Test
    7. public void test() throws IOException {
    8. //根据id查询数据库中的数据
    9. 类名 对象名 = XxxService.getById(id值);
    10. //转换为文档类型
    11. 文档类名 文档对象名 = new 文档类名(对象名);
    12. //序列化Json,这里需要引入fastjson的依赖
    13. String json = JSON.toJSONString(文档对象名);
    14. //准备IndexRequest请求对象,并指定索引库名和文档id
    15. IndexRequest indexRequest = new IndexRequest(索引库名).id(文档id);
    16. //在IndexRequest请求对象中放入Json,并指定参数类型为Json
    17. indexRequest.source(json, XContentType.JSON);
    18. //发送请求
    19. restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
    20. }
    21. }