ElasticSearch基本操作

本文介绍了一个基于Maven项目的Elasticsearch实战案例,包括项目配置、索引操作、搜索查询等功能实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.创建一个maven项目,编写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.immo</groupId>
	<artifactId>elasticsearch</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.4.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.elasticsearch</groupId>
			<artifactId>elasticsearch</artifactId>
			<version>5.6.2</version>
		</dependency>

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

		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

2,编写demo类:

package com.immo.elasticsearch;

import java.net.InetAddress;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetRequestBuilder;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class ElasticSearchDemo {
	private Client client;

	/**
	 * 获取连接
	 * 
	 * @throws Exception
	 */
	@Before
	public void getClient() throws Exception {
		Settings settings1 = Settings.builder().put("cluster.name", "my-elasticsearch")
				.put("client.transport.sniff", true).build();
		client = new PreBuiltTransportClient(Settings.EMPTY)
				.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
	}

	/**
	 * 关闭连接
	 */
	@After
	public void closeClose() {
		client.close();
	}

	/**
	 * 创建索引
	 * 
	 * @throws Exception
	 */
	@Test
	public void createIndex() throws Exception {
		for (int i = 0; i < 100; i++) {

			/**
			 * 第一种
			 */
			/*
			 * XContentBuilder source =
			 * XContentFactory.jsonBuilder().startObject() .field("title", "苹果"
			 * + i) .field("releaseTime", new Date()) .field("price", i * 0.7 *
			 * 5888) .field("message", "这是刚刚发布的苹果手机,准备好肾!!!") .endObject();
			 */
			/**
			 * 这是第二种,还可以传入json和实体类,不一一演示了
			 */
			Map<String, Object> source = new HashMap();
			source.put("title", "苹果" + i);
			source.put("releaseTime", new Date());
			source.put("price", i * 0.7 * 5888);
			source.put("message", "这是刚刚发布的苹果手机,准备好肾!!!");

			// 存json入索引中,setSource可以放入map,或者实体,或者json,能表现key:value形式就好
			IndexResponse response = client.prepareIndex("product", "mobile", "apple" + i).setSource(source).get();
			// 结果获取
			String index = response.getIndex();
			String type = response.getType();
			String id = response.getId();
			long version = response.getVersion();
			System.out.println(index + " : " + type + ": " + id + ": " + version);
		}
	}

	/**
	 * 搜索索引,精准查询
	 */
	@Test
	public void selectIndexById() {
		for (int i = 0; i < 100; i++) {
			// GetResponse response = client.prepareGet("product", "mobile",
			// "apple1")
			// .get();
			GetResponse response = client.prepareGet("product", "mobile", "apple" + i).setOperationThreaded(false) // 线程安全
					.get();
			System.out.println(response.getSourceAsString());
		}
	}

	/**
	 * 按照条件查询
	 * 
	 * @param queryBuilder
	 * @param indexname
	 * @param type
	 */
	@Test
	public void searcher2() {
		// QueryBuilder queryBuilder = QueryBuilders.fuzzyQuery("title", "22");
		// QueryBuilder queryBuilder =
		// QueryBuilders.matchQuery("title","果1");//匹配模式,会把查询的参数分词
		QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery("kimchy", "title", "user", "status"); // title,或者title或者user或者status包含kimchy的数据

		// http://blog.youkuaiyun.com/xiaohulunb/article/details/37877435

		SearchResponse searchResponse = client.prepareSearch("product").setTypes("mobile").setQuery(queryBuilder)
				.execute().actionGet();
		SearchHits hits = searchResponse.getHits();
		System.out.println("查询到记录数=" + hits.getTotalHits());
		SearchHit[] searchHists = hits.getHits();
		if (searchHists.length > 0) {
			for (SearchHit hit : searchHists) {
				Double price = (Double) hit.getSource().get("price");
				String message = (String) hit.getSource().get("message");
				String title = (String) hit.getSource().get("title");
				String id = (String) hit.getId();
				System.out.println(price + "   " + message + "   " + title + "  " + id);
			}
		}
	}

	/**
	 * 删除索引,根据id删除
	 */
	@Test
	public void deleteIndex() {
		DeleteResponse response = client.prepareDelete("product", "mobile", "apple1").get();
		String index = response.getIndex();
		String type = response.getType();
		String id = response.getId();
		long version = response.getVersion();
		System.out.println(index + " : " + type + ": " + id + ": " + version);
	}

	/**
	 * 跟新索引,使用updateRequest对象
	 * 
	 * @throws Exception
	 */
	@Test
	public void updateIndex() throws Exception {
		UpdateRequest updateRequest = new UpdateRequest();
		updateRequest.index("product");
		updateRequest.type("mobile");
		updateRequest.id("apple16");
		updateRequest.doc(XContentFactory.jsonBuilder().startObject()
				// 对没有的字段添加, 对已有的字段替换
				.field("status", "1").field("message", "hello").endObject());
		UpdateResponse response = client.update(updateRequest).get();

		// 打印
		String index = response.getIndex();
		String type = response.getType();
		String id = response.getId();
		long version = response.getVersion();
		System.out.println(index + " : " + type + ": " + id + ": " + version);
	}

	/**
	 * 测试update api, 使用client
	 * 
	 * @throws Exception
	 */
	@Test
	public void updateIndex2() throws Exception {
		// 使用Script对象进行更新
		// UpdateResponse response = client.prepareUpdate("product", "mobile",
		// "apple16")
		// .setScript(new Script("hits._source.status = \"male\""))
		// .get();

		// 使用XContFactory.jsonBuilder() 进行更新
		// UpdateResponse response = client.prepareUpdate("product", "mobile",
		// "apple16")
		// .setDoc(XContentFactory.jsonBuilder()
		// .startObject()
		// .field("status", "malelelele")
		// .endObject()).get();

		// 使用updateRequest对象及script
		// UpdateRequest updateRequest = new UpdateRequest("product", "mobile",
		// "apple16")
		// .script(new Script("ctx._source.status=\"male\""));
		// UpdateResponse response = client.update(updateRequest).get();

		// 使用updateRequest对象及documents进行更新
		UpdateResponse response = client.update(new UpdateRequest("product", "mobile", "apple16")
				.doc(XContentFactory.jsonBuilder().startObject().field("status", "100").endObject())).get();
		System.out.println(response.getIndex());
	}

	/**
	 * 测试update 使用updateRequest
	 * 
	 * @throws Exception
	 * @throws InterruptedException
	 */
	@Test
	public void updateIndex3() throws Exception {
		UpdateRequest updateRequest = new UpdateRequest("product", "mobile", "apple16")
				.script(new Script("ctx._source.status=\"112\""));
		UpdateResponse response = client.update(updateRequest).get();
	}

	/**
	 * 测试upsert方法--更新的时候发现没有这条数据,则插入上面定义的数据,但是所在域和类型和id还是UpdateRequest方法里面设置的那个
	 * 
	 * @throws Exception
	 * 
	 */
	@Test
	public void updateIndex4() throws Exception {
		// 设置查询条件, 查找不到则添加生效
		IndexRequest indexRequest = new IndexRequest("product1", "mobile1", "apple1116").source(XContentFactory
				.jsonBuilder().startObject().field("name", "qergef").field("gender", "malfdsae").endObject());
		// 设置更新, 查找到更新下面的设置
		UpdateRequest upsert = new UpdateRequest("product", "mobile", "apple1112")
				.doc(XContentFactory.jsonBuilder().startObject().field("user", "wenbronk").endObject())
				.upsert(indexRequest);

		client.update(upsert).get();
	}

	/**
	 * 测试multi get api 从不同的index, type, 和id中获取
	 */
	@Test
	public void testMultiGet() {
		MultiGetRequestBuilder prepareMultiGet = client.prepareMultiGet();
		MultiGetResponse multiGetResponse = prepareMultiGet.add("product", "mobile", "apple16", "apple17", "apple18")
				.add("product2", "mobile", "apple16", "apple17", "apple18").add("product", "mobile2", "apple16").get();

		for (MultiGetItemResponse itemResponse : multiGetResponse) {
			GetResponse response = itemResponse.getResponse();
			if (response.isExists()) {
				String sourceAsString = response.getSourceAsString();
				System.out.println(sourceAsString);
			}
		}
	}

	/**
	 * bulk 批量执行 一次查询可以update 或 delete多个document
	 */
	@Test
	public void testBulk() throws Exception {
		BulkRequestBuilder bulkRequest = client.prepareBulk();
		bulkRequest
				.add(client.prepareIndex("twitter", "tweet", "1")
						.setSource(XContentFactory.jsonBuilder().startObject().field("user", "kimchy")
								.field("postDate", new Date()).field("message", "trying out Elasticsearch")
								.endObject()));
		bulkRequest.add(client.prepareIndex("twitter", "tweet", "2")
				.setSource(XContentFactory.jsonBuilder().startObject().field("user", "kimchy")
						.field("postDate", new Date()).field("message", "another post").endObject()));
		BulkResponse response = bulkRequest.get();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值