码迷,mamicode.com
首页 > 其他好文 > 详细

elasticsearch的percolator操作

时间:2017-04-26 23:00:19      阅读:454      评论:0      收藏:0      [点我收藏+]

标签:匹配   type   builder   reg   exce   构建   逻辑   refresh   exe   

  es的普通查询是通过某些条件来查询满足的文档,percolator则不同,先是注册一些条件,然后查询一条文档是否满足其中的某些条件。

     es的percolator特性在数据分类、数据路由、事件监控和预警方面都有很好的应用。

 

       第一步是建立名为percolate的索引,包含一个字段message  

curl -XPUT ‘localhost:9200/percolate‘ -d‘{
     "mappings":{
          "my_type":{
              "properties":{
                   "message":{
                        "type":"string"
                    }
              }
          }
      }
}

       第二步,注册一个percolator查询

       第三步,构建查询

       第四步,查看是否有匹配的条件

       第二步到第四步的代码如下,代码基于es 2.1版本:

QueryBuilder qb = QueryBuilders.termQuery("message", "bonsai");
    try {
        //Index the query = register it in the percolator
        //把查询条件添加到索引中,myDesignatedQueryName为定义的查询名 
        client.prepareIndex("percolate", ".percolator", "myDesignatedQueryName")
            .setSource( XContentFactory.jsonBuilder()
                .startObject()
                    // Register the query,添加查询记录
                    .field("query", qb) 
                .endObject())
            .setRefresh(true) // Needed when the query shall be available immediately
            .execute().actionGet();
        //上面的term查询定义名为:myDesignatedQueryName       

        
        XContentBuilder docBuilder = XContentFactory.jsonBuilder().startObject();
        //This is needed to designate the document
        docBuilder.field("doc").startObject(); 
        docBuilder.field("message", "A new bonsai tree in the office");
        docBuilder.endObject(); 
        docBuilder.endObject(); 

        //Percolate查询
        PercolateResponse response = client.preparePercolate()
                                .setIndices("percolate")
                                .setDocumentType("message")
                             .setSource(docBuilder).execute().actionGet();

       //获取查询query后处理逻辑
        for(PercolateResponse.Match match : response) {
            //创建percolate时指定的ID,根据查询ID在做相应的操作
            System.out.println("percolate ID: "+match.getId());
            System.out.println("percolate Index Name: " +match.getIndex());
        }       
    } catch (ElasticsearchException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

       输出结果为:

percolate ID: myDesignatedQueryName
percolate Index Name: percolate

elasticsearch的percolator操作

标签:匹配   type   builder   reg   exce   构建   逻辑   refresh   exe   

原文地址:http://www.cnblogs.com/lnlvinso/p/6771420.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!