首先声明 我使用的ES版本是2.1,不同版本api可能不尽相同
1、首先创建索引mapping
(1)方法1
- // 创建索引方法1
- public static void createIndex2(String indexName, String indexType) throws IOException {
- Settings settings = Settings.settingsBuilder()
- .put("cluster.name", "cluster_wubing")
- .build();
- InetAddress inetAddress = InetAddress.getByName("192.168.1.107");;
- Client esClient = TransportClient.builder().settings(settings).build()
- .addTransportAddress(new InetSocketTransportAddress(inetAddress, 9300));
- //创建mapping,我这里使用的分词器analyzer/search_analyzer为ik,注意位置location类型为geo_point
- String mapping = "{\"properties\": {\n" +
- " \"id\": {\n" +
- " \"type\": \"integer\",\n" +
- " \"index\": \"not_analyzed\",\n" +
- " \"include_in_all\": false\n" +
- " },\n" +
- " \"title\": {\n" +
- " \"type\": \"string\",\n" +
- " \"store\": \"no\",\n" +
- " \"term_vector\": \"with_positions_offsets\",\n" +
- " \"analyzer\": \"ik_max_word\",\n" +
- " \"search_analyzer\": \"ik_max_word\",\n" +
- " \"include_in_all\": true\n" +
- " },\n" +
- " \"city\": {\n" +
- " \"type\": \"string\",\n" +
- " \"store\": \"no\",\n" +
- " \"term_vector\": \"with_positions_offsets\",\n" +
- " \"analyzer\": \"ik_max_word\",\n" +
- " \"search_analyzer\": \"ik_max_word\",\n" +
- " \"include_in_all\": true\n" +
- " },\n" +
- " \"location\":{\n" +
- " \"type\":\"geo_point\",\n" +
- " \"index\": \"not_analyzed\",\n" +
- " \"include_in_all\": false\n" +
- " }\n" +
- " }}";
- esClient.admin().indices().prepareCreate(indexName).execute().actionGet();
- PutMappingResponse response = esClient.admin().indices().preparePutMapping(indexName)
- .setType(indexType)
- .setSource(mapping)
- .get();
- if (!response.isAcknowledged()) {
- System.out.println("Could not define mapping for type [" + indexName + "]/[" + indexType + "].");
- } else {
- System.out.println("Mapping definition for [" + indexName + "]/["