ElasticSearch之——Java操作ES实例(基于ES-2.3.0)

来源:互联网 发布:天津中为数据 编辑:程序博客网 时间:2024/06/05 04:13

转载请注明出处:http://blog.csdn.net/l1028386804/article/details/78758691

今天,我们就来看看如何利用Java API来操作ES的数据,这里不讲理论的东西了,大家可以参看其他资料了解,这里直接给出实例代码。好了不多说了,我们直接上代码:

1、获取client句柄

/** * 获取client句柄 * @return * @throws Exception */private static Client getClient() throws Exception{//此处的IP是安装ES所在的主机IP地址return TransportClient.builder().build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.209.121"), 9300));}

2、创建索引文件

/** * 创建索引文件  */public static void createIndexFile() throws Exception{XContentBuilder mapping  = XContentFactory.jsonBuilder().startObject().startObject("settings").field("number_of_shards", 1).field("number_of_reolicas", 0).endObject().endObject().startObject().startObject("type_name").startObject("properties").startObject("type").field("type", "string").field("store", "yes").endObject().startObject("eventCount").field("type", "long").field("store", "yes").endObject().startObject("eventDate").field("type","date").field("format", "dateOptionalTime").field("store", "yes").endObject().startObject("message").field("type","string").field("index", "not_analyzed").field("store", "yes").endObject().endObject().endObject().endObject();CreateIndexRequestBuilder builder = getClient().admin().indices().prepareCreate("index_name").setSource(mapping);CreateIndexResponse response = builder.execute().actionGet();if(response.isAcknowledged()){System.out.println("创建索引文档成功!");}else{System.out.println("创建索引文档失败!");}}

3、增加索引文件

/** * 增加文档 * @throws Exception */public static void addIndexFile() throws Exception{IndexResponse response = getClient().prepareIndex("index_name_second", "type_name_second", "1").setSource( XContentFactory.jsonBuilder().startObject().field("type","liuyazhuang").field("eventCount", 1).field("eventDate", new Date()).field("message", "my name is liuyazhuang").endObject()).get();System.out.println("index: " + response.getIndex() + " insert doc id: " + response.getId());}

4、修改索引文件

/** * 修改文档方式1 * @throws Exception */public static void updateIndexFile01() throws Exception{UpdateRequest updateRequest = new UpdateRequest();updateRequest.index("index_name_second");updateRequest.type("type_name_second");updateRequest.id("1");updateRequest.doc( XContentFactory.jsonBuilder().startObject().field("type", "lyz").endObject());System.out.println(getClient().update(updateRequest).get());}/** * 修改文档方式2 * @throws Exception */public static void updateIndexFile02() throws Exception{IndexRequest indexRequest = new IndexRequest("index_name_second", "type_name_second", "3").source(XContentFactory.jsonBuilder().startObject().field("type","liuyazhuang").field("eventCount", 1).field("eventDate", new Date()).field("message", "my name is liuyazhuang").endObject());UpdateRequest request = new UpdateRequest("index_name_second", "type_name_second", "3").doc(XContentFactory.jsonBuilder().startObject().field("type", "lyz").endObject()).upsert(indexRequest);System.out.println(getClient().update(request).get());}

5、查询文件

/** * 查询文档 * @throws Exception */public static void queryIndexFile() throws Exception{GetResponse response = getClient().prepareGet("index_name_second", "type_name_second", "1").get();String source = response.getSource().toString();long version = response.getVersion();String indexName = response.getIndex();String type = response.getType();String id = response.getId();System.out.println("source===>>> " + source + ",  version====>>> " + version + ", indexName=====>>> " + indexName + ", type====>>> " + type + ", id====>>> " + id);}

6、删除文件

/** * 删除文档 * @throws Exception */public static void deleteIndexFile() throws Exception{DeleteResponse response = getClient().prepareDelete("index_name_second", "type_name_second", "1").get();System.out.println(response.isFound());  //文档存在返回true, 不存在返回false}

7、删除索引

/** * 删除索引 * @throws Exception */public static void deleteIndex() throws Exception{DeleteIndexRequest delete = new DeleteIndexRequest("index_name_second");System.out.println(getClient().admin().indices().delete(delete));}

8、完整的操作类

package com.lyz.es.test;import java.net.InetAddress;import java.util.Date;import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;import org.elasticsearch.action.delete.DeleteResponse;import org.elasticsearch.action.get.GetResponse;import org.elasticsearch.action.index.IndexRequest;import org.elasticsearch.action.index.IndexResponse;import org.elasticsearch.action.update.UpdateRequest;import org.elasticsearch.client.Client;import org.elasticsearch.client.transport.TransportClient;import org.elasticsearch.common.transport.InetSocketTransportAddress;import org.elasticsearch.common.xcontent.XContentBuilder;import org.elasticsearch.common.xcontent.XContentFactory;/** * 索引文件的工具类 * @author liuyazhuang * */public class IndexFileUtils {/** * 获取client句柄 * @return * @throws Exception */private static Client getClient() throws Exception{//此处的IP是安装ES所在的主机IP地址return TransportClient.builder().build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.209.121"), 9300));}/** * 创建索引文件  */public static void createIndexFile() throws Exception{XContentBuilder mapping  = XContentFactory.jsonBuilder().startObject().startObject("settings").field("number_of_shards", 1).field("number_of_reolicas", 0).endObject().endObject().startObject().startObject("type_name").startObject("properties").startObject("type").field("type", "string").field("store", "yes").endObject().startObject("eventCount").field("type", "long").field("store", "yes").endObject().startObject("eventDate").field("type","date").field("format", "dateOptionalTime").field("store", "yes").endObject().startObject("message").field("type","string").field("index", "not_analyzed").field("store", "yes").endObject().endObject().endObject().endObject();CreateIndexRequestBuilder builder = getClient().admin().indices().prepareCreate("index_name").setSource(mapping);CreateIndexResponse response = builder.execute().actionGet();if(response.isAcknowledged()){System.out.println("创建索引文档成功!");}else{System.out.println("创建索引文档失败!");}}/** * 增加文档 * @throws Exception */public static void addIndexFile() throws Exception{IndexResponse response = getClient().prepareIndex("index_name_second", "type_name_second", "1").setSource( XContentFactory.jsonBuilder().startObject().field("type","liuyazhuang").field("eventCount", 1).field("eventDate", new Date()).field("message", "my name is liuyazhuang").endObject()).get();System.out.println("index: " + response.getIndex() + " insert doc id: " + response.getId());}/** * 修改文档方式1 * @throws Exception */public static void updateIndexFile01() throws Exception{UpdateRequest updateRequest = new UpdateRequest();updateRequest.index("index_name_second");updateRequest.type("type_name_second");updateRequest.id("1");updateRequest.doc( XContentFactory.jsonBuilder().startObject().field("type", "lyz").endObject());System.out.println(getClient().update(updateRequest).get());}/** * 修改文档方式2 * @throws Exception */public static void updateIndexFile02() throws Exception{IndexRequest indexRequest = new IndexRequest("index_name_second", "type_name_second", "3").source(XContentFactory.jsonBuilder().startObject().field("type","liuyazhuang").field("eventCount", 1).field("eventDate", new Date()).field("message", "my name is liuyazhuang").endObject());UpdateRequest request = new UpdateRequest("index_name_second", "type_name_second", "3").doc(XContentFactory.jsonBuilder().startObject().field("type", "lyz").endObject()).upsert(indexRequest);System.out.println(getClient().update(request).get());}/** * 查询文档 * @throws Exception */public static void queryIndexFile() throws Exception{GetResponse response = getClient().prepareGet("index_name_second", "type_name_second", "1").get();String source = response.getSource().toString();long version = response.getVersion();String indexName = response.getIndex();String type = response.getType();String id = response.getId();System.out.println("source===>>> " + source + ",  version====>>> " + version + ", indexName=====>>> " + indexName + ", type====>>> " + type + ", id====>>> " + id);}/** * 删除文档 * @throws Exception */public static void deleteIndexFile() throws Exception{DeleteResponse response = getClient().prepareDelete("index_name_second", "type_name_second", "1").get();System.out.println(response.isFound());  //文档存在返回true, 不存在返回false}/** * 删除索引 * @throws Exception */public static void deleteIndex() throws Exception{DeleteIndexRequest delete = new DeleteIndexRequest("index_name_second");System.out.println(getClient().admin().indices().delete(delete));}}

9、测试类

package com.lyz.es.test;import org.junit.Test;/** * 测试es * @author liuyazhuang * */public class IndexFileTest {@Testpublic void testCreateIndexFile() throws Exception{IndexFileUtils.createIndexFile();}@Testpublic void testAddIndexFile() throws Exception{IndexFileUtils.addIndexFile();}@Testpublic void testUpdateIndexFile01() throws Exception{IndexFileUtils.updateIndexFile01();}@Testpublic void testQueryIndexFile() throws Exception{IndexFileUtils.queryIndexFile();}@Testpublic void testDeleteIndexFile() throws Exception{IndexFileUtils.deleteIndexFile();}@Testpublic void testDeleteIndex() throws Exception{IndexFileUtils.deleteIndex();}}

10、pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  <modelVersion>4.0.0</modelVersion>  <groupId>com.lyz</groupId>  <artifactId>es</artifactId>  <version>1.0.0-SNAPSHOT</version>  <packaging>jar</packaging>   <dependencies>   <dependency>   <groupId>org.elasticsearch</groupId>   <artifactId>elasticsearch</artifactId>   <version>2.3.0</version>   </dependency>   </dependencies>     <build><finalName>es</finalName><resources><resource><targetPath>${project.build.directory}/classes</targetPath><directory>src/main/resources</directory><filtering>true</filtering><includes><include>**/*.xml</include><include>**/*.properties</include></includes></resource><!-- 结合com.alibaba.dubbo.container.Main --><resource><targetPath>${project.build.directory}/classes/META-INF/spring</targetPath><directory>src/main/resources/spring</directory><filtering>true</filtering><includes><include>spring-context.xml</include></includes></resource></resources><pluginManagement><plugins><!-- 解决Maven插件在Eclipse内执行了一系列的生命周期引起冲突 --><plugin><groupId>org.eclipse.m2e</groupId><artifactId>lifecycle-mapping</artifactId><version>1.0.0</version><configuration><lifecycleMappingMetadata><pluginExecutions><pluginExecution><pluginExecutionFilter><groupId>org.apache.maven.plugins</groupId><artifactId>maven-dependency-plugin</artifactId>  <versionRange>[2.0,)</versionRange>  <goals><goal>copy-dependencies</goal></goals></pluginExecutionFilter><action><ignore /></action></pluginExecution></pluginExecutions></lifecycleMappingMetadata></configuration></plugin></plugins></pluginManagement><plugins><!-- 打包jar文件时,配置manifest文件,加入lib包的jar依赖 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-jar-plugin</artifactId><configuration><classesDirectory>target/classes/</classesDirectory><archive><manifest><mainClass>com.alibaba.dubbo.container.Main</mainClass><!-- 打包时 MANIFEST.MF文件不记录的时间戳版本 --><useUniqueVersions>false</useUniqueVersions><addClasspath>true</addClasspath><classpathPrefix>lib/</classpathPrefix></manifest><manifestEntries><Class-Path>.</Class-Path></manifestEntries></archive></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-dependency-plugin</artifactId><executions><execution><id>copy-dependencies</id><phase>package</phase><goals><goal>copy-dependencies</goal></goals><configuration><type>jar</type><includeTypes>jar</includeTypes><useUniqueVersions>false</useUniqueVersions><outputDirectory>${project.build.directory}/lib</outputDirectory></configuration></execution></executions></plugin></plugins></build></project>

11、温馨提示

大家可以到链接http://download.csdn.net/download/l1028386804/10152051下载Java API操作ElasticSearch的完整实例。


原创粉丝点击