Elasticsearch 邻近查询示例
Elasticsearch 邻近查询示例(全切分分词)
JAVA API方式:
1 SpanNearQueryBuilder span = QueryBuilders.spanNearQuery(); 2 span.clause(QueryBuilders.spanTermQuery("Text", "学")); 3 span.clause(QueryBuilders.spanTermQuery("Text", "联")); 4 span.inOrder(true).slop(1); 5 SearchRequestBuilder rs = client.prepareSearch("weiboall") 6 .setQuery(span).setFrom(0).setSize(20); 7 SearchResponse response = rs.get();
REST方式(JSON):
1 { 2 "from": 0, 3 "size": 20, 4 "query": { 5 "span_near": { 6 "clauses": [ 7 { 8 "span_term": { 9 "Text": { 10 "value": "在" 11 } 12 } 13 }, 14 { 15 "span_term": { 16 "Text": { 17 "value": "讨" 18 } 19 } 20 } 21 ], 22 "slop": 0, 23 "in_order": true 24 } 25 } 26 }
Elasticsearch 邻近查询示例(IK分词)
这种方式利用前后缀组合查询,可以识别查询中的未登陆词、新词等
java API方式:
1 MultiTermQueryBuilder mqb1 = new WildcardQueryBuilder("Text", "*学"); 2 SpanQueryBuilder sb1= new SpanMultiTermQueryBuilder(mqb1); 3 MultiTermQueryBuilder mqb2 = new WildcardQueryBuilder("Text", "联*"); 4 SpanQueryBuilder sb2= new SpanMultiTermQueryBuilder(mqb2); 5 SpanNearQueryBuilder spanb= new SpanNearQueryBuilder(); 6 spanb.clause(sb1); 7 spanb.clause(sb2); 8 spanb.inOrder(true); 9 spanb.slop(0); 10 SearchRequestBuilder rs = client.prepareSearch("weiboall") 11 .setQuery(spanb).setFrom(0).setSize(20); 12 System.out.println(rs.toString()); 13 SearchResponse response = rs.get();
Rest(json)方式:
1 { 2 "from" : 0, 3 "size" : 20, 4 "query" : { 5 "span_near" : { 6 "clauses" : [ { 7 "span_multi" : { 8 "match" : { 9 "wildcard" : { 10 "Text" : { 11 "wildcard" : "*学" 12 } 13 } 14 } 15 } 16 }, { 17 "span_multi" : { 18 "match" : { 19 "wildcard" : { 20 "Text" : { 21 "wildcard" : "联*" 22 } 23 } 24 } 25 } 26 } ], 27 "slop" : 0, 28 "in_order" : true 29 } 30 } 31 }