1.以下是封装了ES常用的基本方法,可以用来做一些简单的测试。
如:获取ES的TransportClient/IndicesAdminClient、判定索引是否存在、创建索引、设置mapping、删除索引、插入文档。
package com.bas.util; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse; import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.IndicesAdminClient; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.transport.client.PreBuiltTransportClient; import java.net.InetAddress; import java.net.UnknownHostException; /** * ES工具类 */ public class ESUtil { //集群名,默认值elasticsearch private static final String CLUSTER_NAME = "TestCluster"; //ES集群中某个节点 private static final String HOSTNAME = "localhost"; //连接端口号 private static final int TCP_PORT = 9300; //构建Settings对象 private static Settings settings = Settings.builder().put("cluster.name", CLUSTER_NAME).build(); //TransportClient对象,用于连接ES集群 private static volatile TransportClient client; /** * 同步synchronized(*.class)代码块的作用和synchronized static方法作用一样, * 对当前对应的*.class进行持锁,static方法和.class一样都是锁的该类本身,同一个监听器 * @return * @throws UnknownHostException */ public static TransportClient getClient(){ if(client==null){ synchronized (TransportClient.class){ try { client=new PreBuiltTransportClient(settings) .addTransportAddress(new TransportAddress(InetAddress.getByName(HOSTNAME), TCP_PORT)); } catch (UnknownHostException e) { e.printStackTrace(); } } } return client; } /** * 获取索引管理的IndicesAdminClient */ public static IndicesAdminClient getAdminClient() { return getClient().admin().indices(); } /** * 判定索引是否存在 * @param indexName * @return */ public static boolean isExists(String indexName){ IndicesExistsResponse response=getAdminClient().prepareExists(indexName).get(); return response.isExists()?true:false; } /** * 创建索引 * @param indexName * @return */ public static boolean createIndex(String indexName){ CreateIndexResponse createIndexResponse = getAdminClient() .prepareCreate(indexName.toLowerCase()) .get(); return createIndexResponse.isAcknowledged()?true:false; } /** * 创建索引 * @param indexName 索引名 * @param shards 分片数 * @param replicas 副本数 * @return */ public static boolean createIndex(String indexName, int shards, int replicas) { Settings settings = Settings.builder() .put("index.number_of_shards", shards) .put("index.number_of_replicas", replicas) .build(); CreateIndexResponse createIndexResponse = getAdminClient() .prepareCreate(indexName.toLowerCase()) .setSettings(settings) .execute().actionGet(); return createIndexResponse.isAcknowledged()?true:false; } /** * 为索引indexName设置mapping * @param indexName * @param typeName * @param mapping */ public static void setMapping(String indexName, String typeName, String mapping) { getAdminClient().preparePutMapping(indexName) .setType(typeName) .setSource(mapping, XContentType.JSON) .get(); } /** * 删除索引 * @param indexName * @return */ public static boolean deleteIndex(String indexName) { DeleteIndexResponse deleteResponse = getAdminClient() .prepareDelete(indexName.toLowerCase()) .execute() .actionGet(); return deleteResponse.isAcknowledged()?true:false; } /** * 插入文档 * @param indexName 索引名 * @param type 类型 * @param doc XContentBuilder */ public static void insertDocument(String indexName, String type, XContentBuilder doc) { IndexResponse response = getClient().prepareIndex(indexName, type) .setSource(doc) .get(); System.out.println(response.status()); } /** * 插入文档 * @param indexName 索引名 * @param type 类型 * @param json Json格式串 */ public static void insertDocument(String indexName, String type, String json) { IndexResponse response = getClient().prepareIndex(indexName, type) .setSource(json, XContentType.JSON) .get(); System.out.println(response.status()); } }
2.结合ESUtil.java ,来做一些测试。首先是创建type为"blog"的Mapping,运行CreateDemo.test():
package com.bas.demo; import com.bas.util.ESUtil; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.client.IndicesAdminClient; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.transport.client.PreBuiltTransportClient; import org.junit.jupiter.api.Test; import java.net.InetAddress; import java.net.UnknownHostException; import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; public class CreateDemo { /** * 创建Index * @param args * @throws UnknownHostException */ public static void main(String[] args) throws UnknownHostException { //1.设置集群名称 Settings settings = Settings.builder().put("cluster.name", "TestCluster").build(); //2.创建client TransportClient client = new PreBuiltTransportClient(settings) .addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300)); //3.获取IndicesAdminClient对象 IndicesAdminClient indicesAdminClient = client.admin().indices(); //4.创建索引 CreateIndexResponse ciReponse=indicesAdminClient.prepareCreate("app_account").get(); System.out.println(ciReponse.isAcknowledged()); } /** * 创建Mapping */ @Test public void test(){ try { XContentBuilder builder = jsonBuilder() .startObject() .startObject("properties") .startObject("id") .field("type", "long") .endObject() .startObject("title") .field("type", "text") .field("analyzer", "ik_max_word") .field("search_analyzer", "ik_max_word") .field("boost", 2) .endObject() .startObject("content") .field("type", "text") .field("analyzer", "ik_max_word") .field("search_analyzer", "ik_max_word") .endObject() .startObject("postdate") .field("type", "date") .field("format", "yyyy-MM-dd HH:mm:ss") .endObject() .startObject("url") .field("type", "keyword") .endObject() .endObject() .endObject(); System.out.println(builder.string()); ESUtil.setMapping("app_account", "blog", builder.string()); } catch (IOException e) { e.printStackTrace(); } } }
3.接下来,以两种方式插入文档到blog:
package com.bas.demo; import com.bas.util.ESUtil; import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; public class InsertDemo { public static void main(String[] args) throws IOException { // 方式一 String json = "{" + ""id":"1"," + ""title":"Java連接ES"," + ""content":"abcdefg。"," + ""postdate":"2019-03-24 14:38:00"," + ""url":"bas.com"" + "}"; System.out.println(json); ESUtil.insertDocument("app_account", "blog", json); // 方式二 XContentBuilder doc = jsonBuilder() .startObject() .field("id","2") .field("title","Java插入数据到ES") .field("content","abcedfasdasd") .field("postdate","2019-03-24 14:38:00") .field("url","bas.com") .endObject(); ESUtil.insertDocument("app_account", "blog", doc); } }