使用 jest 实现 elasticsearch 的CRUD

pom.xml 引用的jar包

<dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
            <version>5.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>5.6.1</version>
        </dependency>

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

        </dependency>

 

代码实现流程

package com.test.controller;

import java.util.List;

import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;


import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.Bulk;
import io.searchbox.core.BulkResult;
import io.searchbox.core.Count;
import io.searchbox.core.CountResult;
import io.searchbox.core.Delete;
import io.searchbox.core.DocumentResult;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.indices.CreateIndex;
import io.searchbox.indices.DeleteIndex;
import io.searchbox.indices.mapping.PutMapping;

public class TestController {

	public static void main(String[] args) throws Exception {
		// 创建链接客户端
		InitElasticSearchConfig clien = new InitElasticSearchConfig("http://127.0.0.1:9200");
		JestClient client = clien.getClient();
		String indexName = "index_item";
		String typeName = "type_item";

		
		
		AppPageVo<ItemEntity> queryResult = splicingQuery(0, 2, "商品", client, indexName, typeName);
		System.out.println(JSON.toJSONString(queryResult));
		
//		List<ItemEntity> entityList = new ArrayList<ItemEntity>();
//		ItemEntity item1 = new ItemEntity();
//		item1.setId(3L);
//		item1.setItemCode("003");
//		item1.setItemTitle("第3个商品3");
//		item1.setSubTitle("第3个商品的副标题");
//		item1.setTag("没有标签");
//		ItemEntity item2 = new ItemEntity();
//		item2.setId(4L);
//		item2.setItemCode("004");
//		item2.setItemTitle("第4个产品4");
//		item2.setSubTitle("第4个产品的副标题");
//		item2.setTag("没有标签");
//		entityList.add(item1);
//		entityList.add(item2);
//		save(entityList, client, indexName, typeName);
		// deleteIndex(client, indexName);
		// createMapping(client, indexName, typeName);

	}

	// 拼接查询语句
	public static AppPageVo<ItemEntity> splicingQuery(Integer startNum, Integer pageSize, String itemTitle,
			JestClient client, String indexName, String typeName) throws Exception {
		if (null == startNum) {
			startNum = 0;
		}
		if (null == pageSize) {
			pageSize = 10;
		}
		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
		BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

		if (!StringUtils.isEmpty(itemTitle)) {
			/**
			 * new QueryStringQueryBuilder("客服").field("title").defaultOperator(Operator.AND);
				则ES检索时,会将“客服” 拆分成 “客”,“服”,检索的结果为title中有 “客”,“服”两个字的即可,不需要两个字相邻,
				如果需要检索包含“客服”的,则需要写成:new QueryStringQueryBuilder("\""+客服+"\"").field("title").defaultOperator(Operator.AND);
			 */
			boolQueryBuilder.must(QueryBuilders.termQuery("itemTitle",itemTitle));

		}

		searchSourceBuilder.query(boolQueryBuilder);

		long total = count(searchSourceBuilder, client, indexName, typeName);

		searchSourceBuilder.size(pageSize).from(startNum);

		List<ItemEntity> objList = search(searchSourceBuilder, client, indexName, typeName);

		AppPageVo<ItemEntity> page = new AppPageVo<ItemEntity>();
		page.setList(objList);
		page.setStartNum(startNum + pageSize);
		page.setTotal((int) total);
		return page;
	}

	//根据条件查询
	public static  List<ItemEntity> search(SearchSourceBuilder searchSourceBuilder, JestClient client, String indexName,
			String typeName) throws Exception {
		try {
			Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(indexName).addType(typeName).build();
			JestResult result = client.execute(search);
			return result.getSourceAsObjectList(ItemEntity.class);
		} catch (Exception e) {
			throw new Exception();
		}
	}

	// 根据条件查询总数
	public static long count(SearchSourceBuilder searchSourceBuilder, JestClient client, String indexName,
			String typeName) throws Exception {
		try {

			Count countBuilder = new Count.Builder().addIndex(indexName).addType(typeName)
					.query(searchSourceBuilder.toString()).build();
			CountResult result = client.execute(countBuilder);

			double count = 0;
			if (null != result.getCount()) {
				count = result.getCount();
			}
			if (!result.isSucceeded()) {
			}
			return (long) (count);

		} catch (Exception e) {
			throw new Exception();
		}
	}

	// 保存或修改文档,当对应索引下的文档不存在则创建,反之则修改
	public static void save(List<ItemEntity> entityList, JestClient client, String indexName, String typeName)
			throws Exception {
		Bulk.Builder bulk = new Bulk.Builder();
		for (ItemEntity entity : entityList) {
			Index index = new Index.Builder(entity).index(indexName).type(typeName).build();
			bulk.addAction(index);
		}
		BulkResult dr = client.execute(bulk.build());
		if (!dr.isSucceeded()) {
			throw new Exception("保存或更新索引文档失败->fail");
		}
		System.out.println("保存或更新索引文档成功->ok");
	}

	// 根据 index/type/id 删除索引
	public static void delete(JestClient client, String id, String indexName, String typeName) throws Exception {
		try {

			DocumentResult dr = client.execute(new Delete.Builder(id).index(indexName).type(typeName).build());
			if (!dr.isSucceeded()) {
				System.out.println("根据index/type/id删除索引出错啦");
			}
			System.out.println(
					"根据index[" + indexName + "]" + ",type[" + typeName + "]" + ",id[" + id + "]" + "删除索引->执行成功ok");
		} catch (Exception e) {
			throw new Exception();
		}

	}

	// 根据index 删除索引
	public static void deleteIndex(JestClient client, String indexName) throws Exception {
		try {
			JestResult dr = client.execute(new DeleteIndex.Builder(indexName).build());
			if (!dr.isSucceeded()) {
				System.out.println("根据index删除索引出错啦");
			}
			System.out.println("根据index[" + indexName + "]删除索引->执行成功ok");
		} catch (Exception e) {
			throw new Exception();
		}
	}

	// 创建索引
	public static void createIndex(JestClient client, String index) {
		try {
			JestResult jestResult = client.execute(new CreateIndex.Builder(index).build());
			System.out.println("createIndex:{}" + jestResult.isSucceeded());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 创建映射(一下代码包含创建索引过程)
	public static void createMapping(JestClient client, String indexName, String typeName) throws Exception {

		try {
			String source = "";
			XContentBuilder mapBuilder = null;
			mapBuilder = XContentFactory.jsonBuilder();
			mapBuilder.startObject().startObject("index").field("analysis.analyzer.default.type", "ik_smart")
					.endObject().endObject();
			source = mapBuilder.string();

			JestResult dr = client.execute(new CreateIndex.Builder(indexName).settings(source).build());// 此处是常见索引

			mapBuilder = XContentFactory.jsonBuilder();
			mapBuilder.startObject().startObject("properties")// Object或者nested类型,下面还有嵌套类型,可以通过properties参数指定。
					.startObject("id").field("type", "long").endObject()// 索引/类型/id
					.startObject("itemCode").field("type", "keyword").endObject()//
					.startObject("itemTitle").field("type", "text").field("analyzer", "ik_smart").endObject()//
					.startObject("subTitle").field("type", "text").field("analyzer", "ik_smart").endObject()//
					.startObject("tag").field("type", "text").field("analyzer", "ik_smart").endObject()//
					.endObject().endObject();//
			source = mapBuilder.string();
			/**
			 * mapBuilder 最终拼接成的格式: { "properties":{ "id":{"type":"long"},
			 * "itemCode":{"type":"keyword"}, "itemTitle":{"type":"text","analyzer":
			 * "ik_smart"}, "subTitle":{"type":"text","analyzer": "ik_smart"} } }
			 */
			PutMapping putMapping = new PutMapping.Builder(indexName, typeName, source).build();
			JestResult jr = client.execute(putMapping);
			if (!jr.isSucceeded()) {
				throw new Exception();
			}
		} catch (Exception e) {
			throw new Exception();
		}
	}
}

 

客户端初始化类:InitElasticSearchConfig

package com.test.controller;

import com.google.gson.GsonBuilder;

import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;

/**
 * 初始化es链接
 * @author MrWang
 *
 */
public class InitElasticSearchConfig {
	private JestClient client ;
	 
    public JestClient getClient() {
        return client;
    }
 
    public InitElasticSearchConfig(String esUrl){
        client = getClientConfig(esUrl) ;
    }
 
    public JestClient getClientConfig(String esUrl){
        JestClientFactory factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig
                .Builder(esUrl)
                .gson(new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create())
                .multiThreaded(true)
                .readTimeout(10000)
                .build());
        JestClient client = factory.getObject();
        return client ;
    }
}

 

ItemEntity 商品实体类

package com.test.controller;

import java.io.Serializable;

import io.searchbox.annotations.JestId;

public class ItemEntity implements Serializable{
	
	@JestId//该注解用于保存获取创建的是后能够直接传该实体,便捷的获取到id
	private Long id;//商品自增id
	private String itemCode;//商品编码
	private String itemTitle;//商品标题
	private String subTitle;//商品副标题
	private String tag;//商品标签
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getItemCode() {
		return itemCode;
	}
	public void setItemCode(String itemCode) {
		this.itemCode = itemCode;
	}
	public String getItemTitle() {
		return itemTitle;
	}
	public void setItemTitle(String itemTitle) {
		this.itemTitle = itemTitle;
	}
	public String getSubTitle() {
		return subTitle;
	}
	public void setSubTitle(String subTitle) {
		this.subTitle = subTitle;
	}
	public String getTag() {
		return tag;
	}
	public void setTag(String tag) {
		this.tag = tag;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值