ElasticSearch6.x 基於SpringBoot 實現ElasticSearch的文檔查詢、更新和刪除管理

SpringBoot 功能封裝涉及ElasticSearch的文檔查詢、更新和刪除方法約定如下:

public BulkByScrollResponse deleteDocumentByCondition(String name, Object text, String[] index);

public DeleteResponse deleteDocumentById(String index, String type, String id)

public GetResponse getDocumentById(String index, String type, String id)

public List<GetResponse> getMultiDocument(String index, String type, List<String> ids)

public UpdateResponse updateDocument(String index, String type, String id, byte[] bytes)

public UpdateResponse updateDocument(String index, String type, String id, Map map)

public UpdateResponse updateDocument(String index, String type, String id, XContentBuilder builder)

public UpdateResponse updateDocumentByScript(String index, String type, String id, String script)

 

在上一篇文中說到:ElasticSearch6.x 基於SpringBoot 實現ElasticSearch連接功能封裝,將約定的方法填充到ElasticSearchIndexUtil.java 工具類中。

@Component
public class ElasticSearchIndexUtil {
	// 引入 Ela 連接實列化對象
	@Autowired
	private TransportClient client;

    /**
	 * 功能描述:刪除文檔
	 * 
	 * @param index
	 *            索引名
	 * @param type
	 *            索引類型
	 * @param id
	 *            文檔ID
	 */
	public DeleteResponse deleteDocumentById(String index, String type, String id) {
		DeleteResponse response = client.prepareDelete(index, type, id).get();
		return response;
	}

	/**
	 * 功能描述:根據條件刪除文檔
	 * 
	 * @param condition
	 *            條件
	 */

	public BulkByScrollResponse deleteDocumentByCondition(String name, Object text, String[] index) {
		DeleteByQueryRequestBuilder builder = DeleteByQueryAction.INSTANCE.newRequestBuilder(client);
		return builder.filter(QueryBuilders.matchQuery(name, text)).source(index).get();
	}


/**
	 * 功能描述:查詢文檔
	 * 
	 * @param index
	 *            索引名
	 * @param type
	 *            索引類型
	 * @param id
	 *            文檔ID
	 */
	public GetResponse getDocumentById(String index, String type, String id) {
		GetResponse response = client.prepareGet(index, type, id).get();
		return response;
	}

/**
	 * 功能描述:根據文檔ID查詢
	 * 
	 * @param index
	 *            索引名
	 * @param type
	 *            索引類型
	 * @param ids
	 *            文檔IDs
	 * @return
	 */
	public List<GetResponse> getMultiDocument(String index, String type, List<String> ids) {
		List<GetResponse> list = new ArrayList<GetResponse>();
		if (ids != null && ids.size() > 0) {
			MultiGetResponse response = client.prepareMultiGet().add(index, type, ids).get();
			if (response != null) {
				for (MultiGetItemResponse item : response) {
					GetResponse getResponse = item.getResponse();
					if (getResponse.isExists()) {
						list.add(getResponse);
						String source = getResponse.getSourceAsString(); // _source
						JSONObject jsonObject = JSON.parseObject(source);
						Set<String> sets = jsonObject.keySet();
						for (String str : sets) {
							System.out.println("key -> " + str);
							System.out.println("value -> " + jsonObject.get(str));
							System.out.println("===============");
						}

					}
				}
			}

		}

		return list;
	}

    /**
	 * 功能描述:根據條件更新文檔
	 * 
	 * @param index
	 *            索引名
	 * @param type
	 *            索引類型
	 * @param id
	 *            文檔ID
	 * @param map
	 *            更新文檔
	 * @throws ExecutionException
	 * @throws InterruptedException
	 */
	public UpdateResponse updateDocument(String index, String type, String id, Map map)
			throws InterruptedException, ExecutionException {
		UpdateRequest update = new UpdateRequest();
		update.index(index);
		update.type(type);
		update.id(id);

		update.doc(map);
		return client.update(update).get();
	}

	/**
	 * 功能描述:根據條件更新文檔
	 * 
	 * @param index
	 *            索引名
	 * @param type
	 *            索引類型
	 * @param id
	 *            文檔ID
	 * @param json
	 *            更新文檔
	 * @throws ExecutionException
	 * @throws InterruptedException
	 */
	public UpdateResponse updateDocument(String index, String type, String id, String json)
			throws InterruptedException, ExecutionException {
		UpdateRequest update = new UpdateRequest();
		update.index(index);
		update.type(type);
		update.id(id);

		update.doc(json);
		return client.update(update).get();
	}

	/**
	 * 功能描述:根據條件更新文檔
	 * 
	 * @param index
	 *            索引名
	 * @param type
	 *            索引類型
	 * @param id
	 *            文檔ID
	 * @param bytes
	 *            更新文檔
	 * @throws ExecutionException
	 * @throws InterruptedException
	 */
	public UpdateResponse updateDocument(String index, String type, String id, byte[] bytes)
			throws InterruptedException, ExecutionException {
		UpdateRequest update = new UpdateRequest();
		update.index(index);
		update.type(type);
		update.id(id);

		update.doc(bytes);
		return client.update(update).get();
	}

	/**
	 * 功能描述:根據條件更新文檔
	 * 
	 * @param index
	 *            索引名
	 * @param type
	 *            索引類型
	 * @param id
	 *            文檔ID
	 * @param builder
	 *            更新文檔
	 * @throws ExecutionException
	 * @throws InterruptedException
	 */
	public UpdateResponse updateDocument(String index, String type, String id, XContentBuilder builder)
			throws InterruptedException, ExecutionException {
		UpdateRequest update = new UpdateRequest();
		update.index(index);
		update.type(type);
		update.id(id);

		update.doc(builder);
		return client.update(update).get();
	}

	/**
	 * 功能描述:根據條件更新文檔
	 * 
	 * @param index
	 *            索引名
	 * @param type
	 *            索引類型
	 * @param id
	 *            文檔ID
	 * @param script
	 *            文檔腳本
	 * @throws ExecutionException
	 * @throws InterruptedException
	 */
	public UpdateResponse updateDocumentByScript(String index, String type, String id, String script)
			throws InterruptedException, ExecutionException {
		UpdateRequest update = new UpdateRequest(index, type, id);
		update.script(new Script(script));
		return client.update(update).get();

	
}

編寫測試工具類Test.java ,測試相關封裝的功能代碼:

@RunWith(SpringRunner.class)
@SpringBootTest
// 由於是Web項目,Junit需要模擬ServletContext,因此我們需要給我們的測試類加上@WebAppConfiguration。
@WebAppConfiguration
public class Test {
	@Autowired
	private ElasticSearchIndexUtil util;

	@org.junit.Test
	public void deleteDocumentByCondition() {
		BulkByScrollResponse response = util.deleteDocumentByCondition("user", (Object) "zzg", new String[] { "book" });
		long number = response.getDeleted();
		System.out.println("文檔刪除數量:" + number);
	}

    @org.junit.Test
	public void deleteDocumentById() {
		DeleteResponse response = util.deleteDocumentById("book", "library", "kxvlA2wBcCFYGDKDNpMc");
		System.out.println(response.toString());
		// 刪除狀態
		RestStatus status = response.status();
		if (status.OK.getStatus() == 200) {
			System.out.println("文檔刪除成功");
		} else {
			System.out.println("文檔刪除失敗");
		}
	}


    @org.junit.Test
	public void getDocumentById() {
		GetResponse response = util.getDocumentById("book", "library", "kBsoA2wBcCFYGDKD55Pg");
		// 文檔屬性
		System.out.println(response.toString());
		Map<String, Object> map = response.getSource();
		Set<String> keySet = map.keySet();
		for (String str : keySet) {
			Object o = map.get(str);
			System.out.println(o.toString());
		}

	}

    @org.junit.Test
	public void getMultiDocument() {
		List<String> ids = Arrays.asList(new String[] { "lBsOBGwBcCFYGDKDy5Nk" });
		List<GetResponse> response = util.getMultiDocument("book", "library", ids);

	}

    @org.junit.Test
	public void updateDocument() {
		Map<String, Object> source = new HashMap<String, Object>();
		source.put("user", "wz");
		source.put("postDate", "2019-07-17");
		try {
			UpdateResponse response = util.updateDocument("book", "library", "lBsOBGwBcCFYGDKDy5Nk", source);
			// 更新文檔屬性
			System.out.println(response.toString());
			Map<String, Object> map = response.getGetResult().getSource();
			Set<String> keySet = map.keySet();
			for (String str : keySet) {
				Object o = map.get(str);
				System.out.println(o.toString());
			}
		} catch (InterruptedException | ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@org.junit.Test
	public void updateDocumentScript() {
		try {
			UpdateResponse response = util.updateDocumentByScript("book", "library", "lBsOBGwBcCFYGDKDy5Nk",
					"ctx._source.user = \"zzg\"");
			System.out.println(response.toString());
		} catch (InterruptedException | ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章