1- [[java-query-percolate-query]]
2- ==== Percolate query
3-
4- See: {ref}/query-dsl-percolate-query.html[Percolate Query]
5-
6- In order to use the `percolate` query from the Java API your
7- the percolator module dependency should be on the classpath and
8- the transport client should be loaded with the percolator plugin:
9-
101[source,java]
112--------------------------------------------------
12- TransportClient transportClient = TransportClient.builder()
13- .settings(Settings.builder().put("node.name", "node"))
14- .addPlugin(PercolatorPlugin.class)
15- .build();
16- transportClient.addTransportAddress(
17- new InetSocketTransportAddress(new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9300))
18- );
3+ Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
4+ TransportClient client = new PreBuiltTransportClient(settings);
5+ client.addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9300)));
196--------------------------------------------------
207
218Before the `percolate` query can be used an `percolator` mapping should be added and
@@ -26,6 +13,7 @@ a document containing a percolator query should be indexed:
2613// create an index with a percolator field with the name 'query':
2714client.admin().indices().prepareCreate("myIndexName")
2815 .addMapping("query", "query", "type=percolator")
16+ .addMapping("docs", "content", "type=text")
2917 .get();
3018
3119//This is the query we're registering in the percolator
@@ -37,7 +25,7 @@ client.prepareIndex("myIndexName", "query", "myDesignatedQueryName")
3725 .startObject()
3826 .field("query", qb) // Register the query
3927 .endObject())
40- .setRefresh(true ) // Needed when the query shall be available immediately
28+ .setRefreshPolicy(RefreshPolicy.IMMEDIATE ) // Needed when the query shall be available immediately
4129 .get();
4230--------------------------------------------------
4331
@@ -51,13 +39,14 @@ code:
5139--------------------------------------------------
5240//Build a document to check against the percolator
5341XContentBuilder docBuilder = XContentFactory.jsonBuilder().startObject();
54- docBuilder.field("doc").startObject(); //This is needed to designate the document
5542docBuilder.field("content", "This is amazing!");
56- docBuilder.endObject(); //End of the doc field
5743docBuilder.endObject(); //End of the JSON root object
44+
45+ PercolateQueryBuilder percolateQuery = new PercolateQueryBuilder("query", "docs", docBuilder.bytes());
46+
5847// Percolate, by executing the percolator query in the query dsl:
5948SearchResponse response = client().prepareSearch("myIndexName")
60- .setQuery(QueryBuilders. percolateQuery("query", ""myDocumentType", docBuilder.bytes() ))
49+ .setQuery(percolateQuery))
6150 .get();
6251//Iterate over the results
6352for(SearchHit hit : response.getHits()) {
0 commit comments