elasticsearch的percolator操作

时间:2025-02-15 12:37:14

  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