Specialized queries

  • more_like_this query(相似度查询)

这个查询能检索到与指定文本、文档或者文档集合相似的文档。

查看More Like This Query

  1. String[] fields = {"name.first", "name.last"}; //fields
  2. String[] texts = {"text like this one"}; //text
  3. Item[] items = null;
  4. QueryBuilder qb = moreLikeThisQuery(fields, texts, items)
  5. .minTermFreq(1) //ignore threshold
  6. .maxQueryTerms(12); //max num of Terms in generated queries
  • script query

该查询允许脚本充当过滤器。 另请参阅 function_score query

查看Script Query

  1. QueryBuilder qb = scriptQuery(
  2. new Script("doc['num1'].value > 1") //inlined script
  3. );

如果已经在每个数据节点上存储名为 `myscript.painless 的脚本,请执行以下操作:

  1. doc['num1'].value > params.param1

然后使用:

  1. QueryBuilder qb = scriptQuery(
  2. new Script(
  3. ScriptType.FILE, //脚本类型 ScriptType.FILE, ScriptType.INLINE, ScriptType.INDEXED
  4. "painless", //Scripting engine 脚本引擎
  5. "myscript", //Script name 脚本名
  6. Collections.singletonMap("param1", 5)) //Parameters as a Map of <String, Object>
  7. );
  • Percolate Query

查看Percolate Query

  1. Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
  2. TransportClient client = new PreBuiltTransportClient(settings);
  3. client.addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9300)));

在可以使用percolate查询之前,应该添加percolator映射,并且应该对包含percolator查询的文档建立索引:

  1. // create an index with a percolator field with the name 'query':
  2. client.admin().indices().prepareCreate("myIndexName")
  3. .addMapping("query", "query", "type=percolator")
  4. .addMapping("docs", "content", "type=text")
  5. .get();
  6. //This is the query we're registering in the percolator
  7. QueryBuilder qb = termQuery("content", "amazing");
  8. //Index the query = register it in the percolator
  9. client.prepareIndex("myIndexName", "query", "myDesignatedQueryName")
  10. .setSource(jsonBuilder()
  11. .startObject()
  12. .field("query", qb) // Register the query
  13. .endObject())
  14. .setRefreshPolicy(RefreshPolicy.IMMEDIATE) // Needed when the query shall be available immediately
  15. .get();

在上面的index中query名为 myDesignatedQueryName

为了检查文档注册查询,使用这个代码:

  1. //Build a document to check against the percolator
  2. XContentBuilder docBuilder = XContentFactory.jsonBuilder().startObject();
  3. docBuilder.field("content", "This is amazing!");
  4. docBuilder.endObject(); //End of the JSON root object
  5. PercolateQueryBuilder percolateQuery = new PercolateQueryBuilder("query", "docs", docBuilder.bytes());
  6. // Percolate, by executing the percolator query in the query dsl:
  7. SearchResponse response = client().prepareSearch("myIndexName")
  8. .setQuery(percolateQuery))
  9. .get();
  10. //Iterate over the results
  11. for(SearchHit hit : response.getHits()) {
  12. // Percolator queries as hit
  13. }