天天看點

Elasticsearch Delete/UpdateByQuery案例

Elasticsearch Delete/UpdateByQuery案例分享

本文涉及技術點:

  • DeleteByQuery/UpdateByQuery
  • Count文檔統計Api

1.準備工作

參考文檔《

高性能elasticsearch ORM開發庫使用介紹

》導入和配置es用戶端

2.編寫建立索引表和初始化資料方法

建立索引表和初始化資料的元件

DocumentCRUD

實作本文不做重點介紹,請通路

視訊教程

了解:

/**
 * 建立索引表并導入測試資料
 */
public void initIndiceAndData(){
   DocumentCRUD documentCRUD = new DocumentCRUD();
   documentCRUD.testCreateIndice();//建立索引表
   documentCRUD.testBulkAddDocument();//導入測試資料
}      

3.定義DeleteByQuery/UpdateByQuery對應的Dsl腳本

建立配置檔案-esmapper/byquery.xml

<properties>
    <!--
        updateByquery
        deleteByquery
        dsl配置之檔案
    -->
    <property name="updateByQuery">
        <![CDATA[
         {
            "query": {
                "bool": {
                    "filter": [
                        {  ## 多值檢索,查找多個應用名稱對應的文檔記錄
                            "terms": {
                                "applicationName.keyword": [#[applicationName1],#[applicationName2]]
                            }
                        },
                        {   ## 時間範圍檢索,傳回對應時間範圍内的記錄,接受long型的值
                            "range": {
                                "agentStarttime": {
                                    "gte": #[startTime],##統計開始時間
                                    "lt": #[endTime]  ##統計截止時間
                                }
                            }
                        }
                    ]
                }
            }
        }
        ]]>
    </property>

    <property name="deleteByQuery">
        <![CDATA[
         {
            "query": {
                "bool": {
                    "filter": [
                        {  ## 多值檢索,查找多個應用名稱對應的文檔記錄
                            "terms": {
                                "applicationName.keyword": [#[applicationName1],#[applicationName2]]
                            }
                        },
                        {   ## 時間範圍檢索,傳回對應時間範圍内的記錄,接受long型的值
                            "range": {
                                "agentStarttime": {
                                    "gte": #[startTime],##統計開始時間
                                    "lt": #[endTime]  ##統計截止時間
                                }
                            }
                        }
                    ]
                }
            }
        }
        ]]>
    </property>
</properties>      

4.實作DeleteByQuery功能

定義實作DeleteByQuery功能的方法

    /**
	 * 驗證DeleteByQuery功能
	 * @throws ParseException
	 */
	public void deleteByQuery() throws ParseException {
		ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil("esmapper/byquery.xml");
		//設定DeleteByQuery查詢條件,通過map傳遞變量參數值,key對于dsl中的變量名稱
		//dsl中有四個變量
		//        applicationName1
		//        applicationName2
		//        startTime
		//        endTime
		Map<String,Object> params = new HashMap<String,Object>();
		//設定applicationName1和applicationName2兩個變量的值
		params.put("applicationName1","blackcatdemo2");
		params.put("applicationName2","blackcatdemo3");
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//設定時間範圍,時間參數接受long值
		params.put("startTime",dateFormat.parse("2017-09-02 00:00:00").getTime());
		params.put("endTime",new Date().getTime());
		//通過count api先查詢資料是否存在
		long totalSize = clientUtil.count("demo","deleteByQuery",params);

		System.out.println("---------------------------------删除前查詢,驗證資料是否存在:totalSize="+totalSize);
		if(totalSize > 0) {//如果有資料,則通過by query删除之,為了實時檢視删除效果,啟用了強制重新整理機制
			//執行DeleteByQuery操作
			String result = clientUtil.deleteByQuery("demo/_delete_by_query?refresh", "deleteByQuery", params);
			System.out.println(result);

			//删除後再次查詢,驗證資料是否被删除成功
			totalSize = clientUtil.count("demo","deleteByQuery",params);
			System.out.println("---------------------------------删除後再次查詢,驗證資料是否被删除:totalSize="+totalSize);
		}

	}      

5.執行DeleteByQuery junit單元測試方法

@Test
	public void testDeleteByQuery() throws ParseException {
		DeleteUdateByQuery deleteUdateByQuery = new DeleteUdateByQuery();
		deleteUdateByQuery.initIndiceAndData();//初始化索引表和測試資料
		deleteUdateByQuery.deleteByQuery();//執行deleteByquery
	}      

6.定義updatebyquery方法

定義兩個updatebyquery方法,一個帶query dsl,一個不帶query dsl:

/**
	 * 驗證simpleUpdateByQuery功能
	 */
	public void simpleUpdateByQuery(){
		ClientInterface clientUtil = ElasticSearchHelper.getRestClientUtil();
		String result = clientUtil.updateByQuery("demo/_update_by_query?conflicts=proceed");
		System.out.println("******************simpleUpdateByQuery result:"+result);
	}

	/**
	 * 驗證帶查詢條件UpdateByQuery功能
	 * @throws ParseException
	 */
	public void updateByQueryWithCondition() throws ParseException {
		ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil("esmapper/byquery.xml");
		//設定查詢條件,通過map傳遞變量參數值,key對于dsl中的變量名稱
		//dsl中有四個變量
		//        applicationName1
		//        applicationName2
		//        startTime
		//        endTime
		Map<String,Object> params = new HashMap<String,Object>();
		//設定applicationName1和applicationName2兩個變量的值
		params.put("applicationName1","blackcatdemo2");
		params.put("applicationName2","blackcatdemo3");
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//設定時間範圍,時間參數接受long值
		params.put("startTime",dateFormat.parse("2017-09-02 00:00:00").getTime());
		params.put("endTime",new Date().getTime());
		String result = clientUtil.updateByQuery("demo/_update_by_query?conflicts=proceed","updateByQuery",params);
		System.out.println("******************updateByQueryWithCondition result:"+result);

	}      

7.執行updatebyquery junit單元測試方法

@Test
public void testUpdateByQuery() throws ParseException {
   DeleteUdateByQuery deleteUdateByQuery = new DeleteUdateByQuery();
   deleteUdateByQuery.initIndiceAndData();//初始化索引表和測試資料
   deleteUdateByQuery.simpleUpdateByQuery();
   deleteUdateByQuery.updateByQueryWithCondition();
}      

8.參考文檔

https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete-by-query.html https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update-by-query.html

本文示例代碼對應的源碼工程位址:

https://gitee.com/bboss/eshelloword

本文對應的java檔案:

https://gitee.com/bboss/eshelloword/blob/master/src/main/java/org/bboss/elasticsearchtest/byquery/DeleteUdateByQuery.java https://gitee.com/bboss/eshelloword/blob/master/src/test/java/org/bboss/elasticsearchtest/crud/DeleteUdateByQueryTest.java

本文對應的dsl配置檔案:

https://gitee.com/bboss/eshelloword/blob/master/src/main/resources/esmapper/byquery.xml