percolate-query.asciidoc 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. [[java-query-percolate-query]]
  2. ==== Percolate query
  3. See: {ref}/query-dsl-percolate-query.html[Percolate Query]
  4. In order to use the `percolate` query from the Java API your
  5. the percolator module dependency should be on the classpath and
  6. the transport client should be loaded with the percolator plugin:
  7. [source,java]
  8. --------------------------------------------------
  9. TransportClient transportClient = TransportClient.builder()
  10. .settings(Settings.builder().put("node.name", "node"))
  11. .addPlugin(PercolatorPlugin.class)
  12. .build();
  13. transportClient.addTransportAddress(
  14. new InetSocketTransportAddress(new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9300))
  15. );
  16. --------------------------------------------------
  17. Before the `percolate` query can be used an `percolator` mapping should be added and
  18. a document containing a percolator query should be indexed:
  19. [source,java]
  20. --------------------------------------------------
  21. // create an index with a percolator field with the name 'query':
  22. client.admin().indices().prepareCreate("myIndexName")
  23. .addMapping("query", "query", "type=percolator")
  24. .get();
  25. //This is the query we're registering in the percolator
  26. QueryBuilder qb = termQuery("content", "amazing");
  27. //Index the query = register it in the percolator
  28. client.prepareIndex("myIndexName", "query", "myDesignatedQueryName")
  29. .setSource(jsonBuilder()
  30. .startObject()
  31. .field("query", qb) // Register the query
  32. .endObject())
  33. .setRefresh(true) // Needed when the query shall be available immediately
  34. .get();
  35. --------------------------------------------------
  36. This indexes the above term query under the name
  37. *myDesignatedQueryName*.
  38. In order to check a document against the registered queries, use this
  39. code:
  40. [source,java]
  41. --------------------------------------------------
  42. //Build a document to check against the percolator
  43. XContentBuilder docBuilder = XContentFactory.jsonBuilder().startObject();
  44. docBuilder.field("doc").startObject(); //This is needed to designate the document
  45. docBuilder.field("content", "This is amazing!");
  46. docBuilder.endObject(); //End of the doc field
  47. docBuilder.endObject(); //End of the JSON root object
  48. // Percolate, by executing the percolator query in the query dsl:
  49. SearchResponse response = client().prepareSearch("myIndexName")
  50. .setQuery(QueryBuilders.percolateQuery("query", ""myDocumentType", docBuilder.bytes()))
  51. .get();
  52. //Iterate over the results
  53. for(SearchHit hit : response.getHits()) {
  54. // Percolator queries as hit
  55. }
  56. --------------------------------------------------