使用Java API 操作ElasticSearch
ES本身是Java做的,对Java的支持很好,ES提供了功能强大、易用的Java API,所有的ES功能都可以使用客户端对象来执行,所有操作在本质上完全异步的。此外,客户机上的操作可以单独执行,也可以批量执行。
注意,Java客户端和服务器端的ES尽量版本一致。
引入pom文件
<dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>6.2.3</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <version>6.2.3</version> </dependency>
创建一个工具类
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 java.net.InetAddress; //简化ES操作的工具类 public class ESHelper { public static final String indexName="indextest";//索引名 public static final String documentType="product";//索引类型 public static TransportClient client=null; static { //ES配置 Settings settings=Settings.builder().put("cluster.name","my-es")//集群名称 .put("client.transport.sniff",true)//是否自动检测 .build(); try{ client=new PreBuiltTransportClient(settings). addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.188.8")//es 主机地址 ,9300));//端口号 }catch (Exception e){ e.printStackTrace(); } } public static TransportClient getClient() { return client; } }
创建索引
//创建索引库 @Test public void createIndex(){ CreateIndexResponse response = ESHelper.getClient().admin()//admin权限 .indices()//索引集合 .prepareCreate(ESHelper.indexName)//索引名 .execute().actionGet();//请求 if(response.isAcknowledged()){ System.out.println("add Index OK"); }else{ System.out.println("add Index NO"); } }
添加文档
//添加文档 @Test public void addDocument(){ Book book=new Book(2,"死亡","毕淑敏",new Date());//创建一个Book对象 Map<String,Book> map=new HashMap<>();//创建一个Map将Book对象传进去 map.put(book.getId().toString(),book); IndexResponse response = ESHelper.getClient().prepareIndex(ESHelper.indexName, ESHelper.documentType).setId(book.getId().toString()).setSource(map).get(); System.out.println(response.getResult()); }
获取数据
//获取数据 @Test public void getDocument(){ GetResponse documentFields = ESHelper.getClient().prepareGet(ESHelper.indexName, ESHelper.documentType, "1").get(); System.out.println(documentFields.getSourceAsString()); }
修改数据
//修改数据 @Test public void updateData(){ Book book=new Book(1,"艰难的抉择","卡莉",new Date()); Map<String,Book> map=new HashMap<>(); map.put(book.getId().toString(),book); UpdateRequest updateRequest=new UpdateRequest(); updateRequest.index(ESHelper.indexName);//索引库 updateRequest.type(ESHelper.documentType);//类型 updateRequest.id("1");//修改的id updateRequest.doc(map); ESHelper.getClient().update(updateRequest).actionGet(); System.out.println("Update OK"); }
删除索引
//删除数据 @Test public void deleteData(){ ESHelper.getClient().prepareDelete(ESHelper.indexName,ESHelper.documentType,"1").get(); }
删除数据
//删除索引 @Test public void deleteIndex(){ ESHelper.getClient().admin().indices().delete(new DeleteIndexRequest("test")); System.out.println("DELETE OK"); }