Elasticsearch returns parent-child data association query case sharing

    In the article " Elasticsearch Parent-Child Relationship Maintenance and Retrieval Case Sharing ", the basic functions of Elasticsearch parent-child relationship maintenance and retrieval are introduced. This article continues the previous document and shares the Elasticsearch associated query case that returns parent-child data at the same time.

The technical points involved in this article:

  1. The use of inner_hits returns both parent table data and child table data through inner_hits
  2. Parent-child two-way data retrieval and result binding and traversal

1. Preparations

Refer to the document " Introduction to the use of high-performance elasticsearch ORM development library " to import and configure es client

2. Define the dsl retrieval statement with inner_hits

Add two dsl retrieval statements to the dsl configuration file -esmapper/indexparentchild.xml:

hasChildSearchReturnParent2ndChildren demonstrates that when retrieving company data according to employee information, it returns the employee information under the qualified company at the same time

hasParentSearchByCountryReturnParent2ndChildren demonstrates that when retrieving employee data according to company information, the company information corresponding to the eligible employees is returned at the same time

    <!--以雇员姓名为条件检索公司信息并返回公司雇员信息-->
    <property name="hasChildSearchReturnParent2ndChildren">
        <![CDATA[
            {
              "query": {
                "has_child": {
                  "type":       "employee",
                  "score_mode": "max",
                  "query": {
                    "match": {
                      "name": #[name] ##雇员名称参数
                    }
                  },
                  "inner_hits": {} ## 这是同时返回父子数据的关键所在
                }
              }
            }
        ]]>
    </property>
    <!--根据公司所在的国家信息检索员工信息,同时返回员工所属的公司信息-->
    <property name="hasParentSearchByCountryReturnParent2ndChildren">
        <![CDATA[
            {
              "query": {
                "has_parent": {
                  "type": "company",
                  "query": {
                    "match": {
                      "country": #[country] ##国家代码参数
                    }
                  },
                  "inner_hits": {} ## 这是同时返回父子数据的关键所在
                }
              }
            }
        ]]>
    </property>

3. Define the retrieval operation method

Add the following method to the file  ParentChildTest.java


	/**
	 * 检索公司信息,并返回公司对应的雇员信息(符合检索条件的雇员信息)
	 */
	public void hasChildSearchReturnParent2ndChildren(){
		ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil("esmapper/indexparentchild.xml");
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("name","Alice Smith");

		try {
			ESInnerHitSerialThreadLocal.setESInnerTypeReferences(Employee.class);//指定inner查询结果对于雇员类型
			ESDatas<Company> escompanys = clientUtil.searchList("company/company/_search","hasChildSearchReturnParent2ndChildren",params,Company.class);
			long totalSize = escompanys.getTotalSize();
			List<Company> companyList = escompanys.getDatas();//获取符合条件的公司
			//查看公司下面的雇员信息(符合检索条件的雇员信息)
			for (int i = 0; i < companyList.size(); i++) {
				Company company = companyList.get(i);
				List<Employee> employees = ResultUtil.getInnerHits(company.getInnerHits(), "employee");
				System.out.println(employees.size());
			}
		}
		finally{
			ESInnerHitSerialThreadLocal.clean();//清空inner查询结果对于雇员类型
		}
	}
	/**
	 * 通过公司所在国家检索雇员信息,并返回雇员对应的公司信息
	 */
	public void hasParentSearchByCountryReturnParent2ndChildren(){

		ClientInterface clientUtil = ElasticSearchHelper.getConfigRestClientUtil("esmapper/indexparentchild.xml");
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("country","UK");

		try {
			ESInnerHitSerialThreadLocal.setESInnerTypeReferences(Company.class);//指定inner查询结果对于公司类型
			ESDatas<Employee> escompanys = clientUtil.searchList("company/employee/_search","hasParentSearchByCountryReturnParent2ndChildren",params,Employee.class);
			List<Employee> employeeList = escompanys.getDatas();//获取符合条件的雇员数据
			long totalSize = escompanys.getTotalSize();
			//查看每个雇员对应的公司信息
			for(int i = 0;  i < employeeList.size(); i ++) {
				Employee employee = employeeList.get(i);
				List<Company> companies = ResultUtil.getInnerHits(employee.getInnerHits(), "company");
				System.out.println(companies.size());
			}
		}
		finally{
			ESInnerHitSerialThreadLocal.clean();//清空inner查询结果对于公司类型
		}
	}

illustrate:

1) The data object type to be returned in inner_hits is specified through ESInnerHitSerialThreadLocal

ESInnerHitSerialThreadLocal.setESInnerTypeReferences(Employee.class);//Specify inner query result for employee type
ESInnerHitSerialThreadLocal.setESInnerTypeReferences(Company.class);//Specify the inner query result for the company type

Need to clean up after use:

ESInnerHitSerialThreadLocal.clean();//Clear inner query results for employee type

2) The employee.getInnerHits() and company.getInnerHits() methods are both methods inherited from ESBaseData, bboss will automatically set the parent-child related data retrieved by inner_hits to the ESBaseData object, and the corresponding data can be obtained through the getInnerHits() method ;

3) The ResultUtil.getInnerHits tool is used to obtain the associated result set. The second parameter of the method corresponds to the type and name retrieved by inner_hits:

List<Employee> employees = ResultUtil.getInnerHits(company.getInnerHits(), "employee");       

List<Company> companies = ResultUtil.getInnerHits(employee.getInnerHits(), "company");

4. Execute the test method

Through junit, execute the new test method

@Test
public void testFromJson(){
   createIndice();
   importFromJsonData();
   hasChildSearchByBirthday();
   this.hasChildSearchByName();
   this.hasChildSearchByMinChild();
   this.hasParentSearchByCountry();

   this.hasChildSearchReturnParent2ndChildren();//The method corresponding to this article
   this.hasParentSearchByCountryReturnParent2ndChildren();//The method corresponding to this article
}

5. Reference Documentation

https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-request-inner-hits.html#nested-inner-hits

6. Development communication 

elasticsearch technical exchange group: 166471282 elasticsearch WeChat
public account: bbossgroups 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324417517&siteId=291194637