使用 Java API 操作 elasticsearch

maven 依赖


<dependencies>
	<!-- https://mvnrepository.com/artifact/junit/junit -->
	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.12</version>
		<scope>test</scope>
	</dependency>

	<dependency>
		<groupId>org.elasticsearch</groupId>
		<artifactId>elasticsearch</artifactId>
		<version>5.2.2</version>
	</dependency>

	<dependency>
		<groupId>org.elasticsearch.client</groupId>
		<artifactId>transport</artifactId>
		<version>5.2.2</version>
	</dependency>

	<dependency>
		<groupId>org.apache.logging.log4j</groupId>
		<artifactId>log4j-core</artifactId>
		<version>2.9.0</version>
	</dependency>
</dependencies>

 

代码示例


获取 client

@Before
public void getClient() throws UnknownHostException {
	Settings settings = Settings.builder().put("cluster.name", "my-application").build();
	client = new PreBuiltTransportClient(settings);
	client.addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress("112.124.1.100", 9300)));
}

 

 

创建 Index

@Test
public void createIndex() {
//  创建一个名称为 blog 的索引
	CreateIndexResponse response = client.admin().indices().prepareCreate("blog").execute().actionGet();
}

 

删除 Index

@Test
public void deleteIndex() {
//	删除名为 blog 的 Index
	DeleteIndexResponse response = client.admin().indices().prepareDelete("blog").execute().actionGet();
}

 

创建 Document

@Test
public void createDocument() {
	String source = "{\"content\": \"我是内容!\"}";
	IndexResponse response = client.prepareIndex("blog", "article", "1").setSource(source).execute().actionGet();
}
@Test
public void createDocument() throws IOException {
	XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("name", "姜春波").endObject();
	IndexResponse response = client.prepareIndex("blog", "article", "2").setSource(builder).execute().actionGet();
}

 

搜索 Document

@Test
public void get() {
	GetResponse response = client.prepareGet("blog", "article", "2").execute().actionGet();
	System.out.println(response.getSourceAsString());
}
@Test
public void getMulti() {
//		获取多个索引
	MultiGetResponse response = client.prepareMultiGet()
			.add("blog", "article", "2")
			.add("blog", "article", "1")
			.execute().actionGet();
//		获取 Item Response 数组
	MultiGetItemResponse[] responses = response.getResponses();
//		遍历
	for (MultiGetItemResponse multiGetItemResponse : responses) {
		GetResponse response0 = multiGetItemResponse.getResponse();
		boolean exists = response0.isExists();
		if (exists) {
			System.out.println(response0.getSourceAsString());
		}
	}
}

 

 

更新 Document

如果 ES 的 Document 不存在,会抛异常;如果 ES 的 field 不存在会自动补充。

@Test
public void updateDocument() throws IOException, InterruptedException, ExecutionException {
//		创建 UpdateRequest
	UpdateRequest updateRequest = new UpdateRequest("blog", "article", "1");
	updateRequest.doc(XContentFactory.jsonBuilder().startObject()
			.field("id", "2")
			.field("title", "Java 成神之路")
			.field("content", "无字")
			.endObject());
	client.update(updateRequest).get();
}

 

更新 or 保存 Document

@Test
public void updateOrSave() throws IOException, InterruptedException, ExecutionException {
//		创建 source
	XContentBuilder source = XContentFactory.jsonBuilder().startObject()
		.field("id", "2")
		.field("title", "呵呵哒")
		.field("content", "看片").endObject();
	IndexRequest request = new IndexRequest("blog", "article", "1").source(source);
	UpdateRequest updateRequest = new UpdateRequest("blog", "article", "1")
			.doc(source).upsert(request);
	updateRequest.doc(source);
	client.update(updateRequest).get();
}

 

删除 Document

@Test
public void delete() {
	DeleteResponse response = client.prepareDelete("blog", "article", "4").get();
}

 

 

条件查询

全部查询

@Test
public void search() {
	SearchResponse response = client.prepareSearch("blog").setTypes("article").setQuery(QueryBuilders.matchAllQuery()).get();
	SearchHits hits = response.getHits();
	System.out.println("查询" + hits.getTotalHits());
	Iterator<SearchHit> iterator = hits.iterator();
	while(iterator.hasNext()) {
		SearchHit next = iterator.next();
		System.out.println(next.getSourceAsString());
	}
}

分词查询

@Test
public void search2() {
	SearchResponse response = client.prepareSearch("blog").setTypes("article")
			.setQuery(QueryBuilders.queryStringQuery("看毛片啊")).get();
	SearchHits hits = response.getHits();
	System.out.println("查询" + hits.getTotalHits());
	Iterator<SearchHit> iterator = hits.iterator();
	while (iterator.hasNext()) {
		SearchHit next = iterator.next();
		System.out.println(next.getSourceAsString());
	}
}

词条查询

@Test
public void search3() {
	SearchResponse response = client.prepareSearch("blog").setTypes("article")
			.setQuery(QueryBuilders.termQuery("content", "看片")).get();
	SearchHits hits = response.getHits();
	System.out.println("查询" + hits.getTotalHits());
	Iterator<SearchHit> iterator = hits.iterator();
	while (iterator.hasNext()) {
		SearchHit next = iterator.next();
		System.out.println(next.getSourceAsString());
	}
}

 

©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页