定义创建索引库的Json参数

:::tips 新建一个常量类,用来存储创建索引库的Json参数常量 :::

  1. public class XxxConstants {
  2. //mapping映射的字段串常量
  3. public static final String MAPPING_TEMPLATE = "{\n" +
  4. " \"mappings\": {\n" +
  5. " \"properties\": {\n" +
  6. " \"id\": {\n" +
  7. " \"type\": \"long\"\n" +
  8. " },\n" +
  9. " \"name\":{\n" +
  10. " \"type\": \"text\",\n" +
  11. " \"analyzer\": \"ik_max_word\",\n" +
  12. " \"copy_to\": \"all\"\n" +
  13. " },\n" +
  14. " \"address\":{\n" +
  15. " \"type\": \"keyword\",\n" +
  16. " \"index\": false\n" +
  17. " },\n" +
  18. " \"price\":{\n" +
  19. " \"type\": \"integer\"\n" +
  20. " },\n" +
  21. " \"score\":{\n" +
  22. " \"type\": \"integer\"\n" +
  23. " },\n" +
  24. " \"brand\":{\n" +
  25. " \"type\": \"keyword\",\n" +
  26. " \"copy_to\": \"all\"\n" +
  27. " },\n" +
  28. " \"city\":{\n" +
  29. " \"type\": \"keyword\",\n" +
  30. " \"copy_to\": \"all\"\n" +
  31. " },\n" +
  32. " \"starName\":{\n" +
  33. " \"type\": \"keyword\"\n" +
  34. " },\n" +
  35. " \"business\":{\n" +
  36. " \"type\": \"keyword\"\n" +
  37. " },\n" +
  38. " \"location\":{\n" +
  39. " \"type\": \"geo_point\"\n" +
  40. " },\n" +
  41. " \"pic\":{\n" +
  42. " \"type\": \"keyword\",\n" +
  43. " \"index\": false\n" +
  44. " },\n" +
  45. " \"all\":{\n" +
  46. " \"type\": \"text\",\n" +
  47. " \"analyzer\": \"ik_max_word\"\n" +
  48. " }\n" +
  49. " }\n" +
  50. " }\n" +
  51. "}";
  52. }

创建索引库

  1. @SpringBootTest
  2. public class MyTest{
  3. //注入RestHighLevelClient对象
  4. @Autowired
  5. private RestHighLevelClient restHighLevelClient;
  6. @Test
  7. public void test() throws IOException {
  8. //创建CreateIndexRequest请求对象,并指定索引库名
  9. CreateIndexRequest createIndexRequest = new CreateIndexRequest(索引库名);
  10. //在CreateIndexRequest请求对象中放入创建索引库的Json参数,并指定参数类型为Json
  11. createIndexRequest.source(MAPPING_TEMPLATE, XContentType.JSON);
  12. //发送请求
  13. restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
  14. }
  15. }