首页 > 代码库 > Elasticsearch Java API 续

Elasticsearch Java API 续

1、使用multi get API可以通过索引名、类型名、文档id一次得到一个文档集合,文档可以来自同一个索引库,也可以来自不同索引库。示例如下:


MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
    .add("twitter", "tweet", "1")    //注释1                            
    .add("twitter", "tweet", "2", "3", "4")     //注释2             
    .add("another", "type", "foo")          //注释3                   
    .get();

for (MultiGetItemResponse itemResponse : multiGetItemResponses) {       //注释4
    GetResponse response = itemResponse.getResponse();
    if (response.isExists()) {                   //注释5               
        String json = response.getSourceAsString();    //注释6                 
    }
}

注释1: 通过单一的ID获取一个文档. 

注释2:传入多个id,从相同的索引名/类型名中获取多个文档. 
注释3:可以同时获取不同索引中的文档. 
注释4:遍历结果集. 
注释5:检验文档是否存在. 
注释6:获取文档源.

2、要在Java中实现一个有三级父子关系的嵌套搜索,相关资料很少,发在stackoverflow上以后一个Switzerland的大神很快回复了我,google+stackoverflow很好使。对应的命令行query:

{
      "query": {
        "has_child": {
          "type": "instance",
          "query": {
            "has_child": {
              "type": "instance_permission",
              "query": {
                "terms": {
                  "uuid": {
                    "index": "user",
                    "type": "user",
                    "id": "5",
                    "path": "uuids"
                  }
                }
              }
            }
          }
        }
      }
    }

Java api:

TermsLookupQueryBuilder terms = QueryBuilders
                    .termsLookupQuery("uuid")
                    .lookupIndex("user")
                    .lookupType("user")
                    .lookupId("5")
                    .lookupPath("uuids");

HasChildQueryBuilder   hQuery = QueryBuilders
                       .hasChildQuery("instance", QueryBuilders
                       .hasChildQuery("instance_permission", terms));

System.out.println("Exectuing Query 1");
System.out.println(hQuery.toString());
SearchResponse searchResponse1 = client
              .prepareSearch("foo_oa_hr_askforleave")
                .setQuery(hQuery).execute().actionGet();

System.out.println("There were " + searchResponse1.getHits().getTotalHits()
                         + " results found for Query 1.");
System.out.println(searchResponse1.toString());
System.out.println();

Elasticsearch Java API 续