maven项目使用java接口连接elasticsearch,基本操作:增删改查

创建maven项目,创建myElasticSearch.java文件,在App.java(默认创建文件)中的Main()执行。


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.test</groupId>
  <artifactId>myES</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>myES</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
	    <groupId>org.elasticsearch</groupId>
	    <artifactId>elasticsearch</artifactId>
	    <version>2.3.0</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
	<dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-databind</artifactId>
	    <version>2.6.2</version>
	</dependency>
  </dependencies>
</project>

myElasticSearch.java

package com.test.myES;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

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.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
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.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import static org.elasticsearch.common.xcontent.XContentFactory.*;



public class myElasticSearch{
	
	//private Logger logger
	public final static String HOST = "127.0.0.1";
	public final static int PORT = 9300;
	public final static String _cluster_name = "my_ElasticcSearch_10";
	public final static String _index = "es1024";
	
	public final static String _type = "t_link";
	public Client client = null;
	
	public myElasticSearch(){
		
	}
	
	public void openConnectES() throws UnknownHostException{
		Settings settings = Settings.settingsBuilder()
				.put("cluster.name", "my_ElasticcSearch_10").build();
		client = TransportClient.builder().settings(settings).build()
				.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
	}
	public void closeConnectES(){
		client.close();
	}
	
	//创建索引index--类似于数据库
	public void createIndex() throws IOException{
		XContentBuilder mapping = XContentFactory.jsonBuilder()
				.startObject()
					.startObject("settings")
						.field("number_of_shards", 2)	//分片数量
						.field("number_of_replicas", 0)	//副本数量
					.endObject()
				.endObject()
				.startObject()
					.startObject("t_type")	//表名称
						.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("stroe","yes")
							.endObject()
							.startObject("message").field("type", "string")
								.field("index", "not_analyzed").field("stroe", "yes")
							.endObject()
						.endObject()
					.endObject()
				.endObject();
		CreateIndexRequestBuilder cirb = client.admin().indices()
				.prepareCreate("i_index")
				.setSource(mapping);
		CreateIndexResponse response = cirb.execute().actionGet();
		if(response.isAcknowledged()){
			System.out.println("Index created.");
		}else{
			System.err.println("Index creation failed.");
		}
		
	}
	public void insert() throws IOException{
		IndexResponse response = client
				.prepareIndex("i_index", "t_type", "1")
				.setSource(
						jsonBuilder().startObject()
						.field("type", "syslog")
						.field("eventCount", 1)
						.field("eventDate", new Date())
						.field("message", "i_index insert doc test")
					.endObject()).get();
		System.out.println("index"+response.getIndex()
								+" insert doc id:"+response.getId()
								+" result:"+response.isCreated());
	}
	public void update() throws IOException, InterruptedException, ExecutionException{
		UpdateRequest updateRequest = new UpdateRequest();
		updateRequest.index("i_index");
		updateRequest.type("t_type");
		updateRequest.id("1");
		updateRequest.doc(
				jsonBuilder()
				.startObject().field("type", "file").endObject());
		client.update(updateRequest).get();
	}
	public void updateIfNoExist() throws IOException, InterruptedException, ExecutionException{
		IndexRequest indexRequest = new IndexRequest("i_index", "t_type", "100")
			.source(jsonBuilder()
				.startObject()
					.field("type", "syslog")
					.field("eventCount", 2)
					.field("eventDate", new Date())
					.field("message", "i_index insert doc test")
				.endObject());
		UpdateRequest updateRequest = new UpdateRequest("i_index", "t_type", "100")
			.doc(jsonBuilder().startObject().field("type","file").endObject())
			.upsert(indexRequest);	//upsert:更新插入
		client.update(updateRequest).get();
	}
	
	public void delete(){
		//删除文档
		DeleteResponse deleteReponse = client.prepareDelete("i_index", "t_type", "100").get();
		boolean isFound = deleteReponse.isFound();
		
		//删除索引
		DeleteIndexRequest delete = new DeleteIndexRequest("i_index");
		client.admin().indices().delete(delete);
	}
	
	public void query() throws UnknownHostException{
		GetResponse response = client.prepareGet(_index, _type, "11056").get();
		String source = response.getSource().toString();
		long version = response.getVersion();
		String indexName = response.getIndex();
		String type = response.getType();
		String id = response.getId();		
		
/*
		Settings settings = Settings.settingsBuilder().put("cluster.name", "my_ElasticcSearch_10").build();
		 
		try {
 
			Client client = TransportClient.builder().settings(settings).build()
					.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
 
			// 批量创建索引
			BulkRequestBuilder bulkRequest = client.prepareBulk();
			Map<String, Object> map = new HashMap<>();
			map.put("link", "Jack");
 
			IndexRequest request = client.prepareIndex("es1024", "t_link").setSource(map).request();
			bulkRequest.add(request);
			BulkResponse bulkResponse = bulkRequest.execute().actionGet();
			if (bulkResponse.hasFailures()) {
				System.out.println("批量创建索引错误!");
			}
			
			GetResponse response = client.prepareGet("es1024", "t_link", "11056").get();
			String source = response.getSource().toString();
			
			client.close();
			System.out.println("批量创建索引成功");
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
*/
	}
}

 


App.java

package com.test.myES;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args ) throws IOException, InterruptedException, ExecutionException
    {
    	myElasticSearch m = new myElasticSearch();
    	m.openConnectES();
    	//m.createIndex();			//创建索引(数据库)
    	//m.insert();				//插入一列数据(数据库)
    	//m.update();					//更新数据
    	//m.delete();
    	//m.query();
    	m.closeConnectES();
        System.out.println( "Hello World!" );
    }
}

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百草疯茂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值