elasticsearch的percolator操作

  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

转载于:https://www.cnblogs.com/lnlvinso/p/6771420.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值