当前位置: 首页 > elasticsearch, 搜索 > 正文

elasticsearch customScoreQuery 实例

1 星2 星3 星4 星5 星 (2 次投票, 评分: 5.00, 总分: 5)
Loading ... Loading ...
baidu_share

我们来学习一下elasticsearch customScoreQuery 的使用。customScoreQuery 可以自定义score,从而来影响排序结果。

建立mapping

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
	public static XContentBuilder createMapping(String indexName){
		XContentBuilder mapping = null;
		try {
			mapping = jsonBuilder()
					.startObject()
						// 索引库名(类似数据库中的表)
						.startObject(indexName)
 
							.startObject("properties")
								// 新闻ID
								.startObject("id")
									.field("type", "long")
									.field("store", "yes")
									.field("index", "not_analyzed")
									.field("include_in_all", "false")
								.endObject()
 
								// title
								.startObject("titele")
									.field("type", "string")
									.field("store", "yes")
									.field("term_vector","with_positions_offsets")
									.field("indexAnalyzer", "ik")
									.field("searchAnalyzer", "ik")
									.field("include_in_all", "false")
									.field("boost", 4.0) // 打分(默认1.0)
								.endObject()
                                .startObject("updatetime")
									.field("type", "string")
									.field("store", "yes")
									.field("include_in_all", "false")
								.endObject()
							.endObject()
						.endObject()
					.endObject();
		} catch (IOException e) {
			e.printStackTrace();
		}
 
		return mapping;
	}

创建索引

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	public static void createIndex(String indexName, String indexType){
 
 
	    Client esClient = ESServiceSingleton2.getTransportClient();
 
	    // 创建Mapping
	    XContentBuilder mapping = createMapping(indexName);
		// 创建一个空索引
 
	    esClient.admin().indices().prepareCreate(indexName).execute().actionGet();
 
		PutMappingRequest mappingRequest = Requests.putMappingRequest(indexName).type(indexType).source(mapping);
		esClient.admin().indices().putMapping(mappingRequest).actionGet();
 
 
	}

添加索引数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
	public static Integer addIndex(String indexName, String indexType){
 
 
	    Client esClient = ESServiceSingleton2.getTransportClient();
 
 
		BulkRequestBuilder bulkRequest = esClient.prepareBulk();   
 
 
		try{
		bulkRequest.add(esClient.prepareIndex(indexName, indexType, ""+5)   
	  			.setSource(jsonBuilder()
						.startObject()
							.field("id", 1)
 
							.field("title", "脱北者中国")
							.field("updatetime","1370563200")
						.endObject())
			        );
		bulkRequest.add(esClient.prepareIndex(indexName, indexType, ""+2)   
	  			.setSource(jsonBuilder()
						.startObject()
							.field("id", 2)
 
							.field("title", "脱北者中国")
							.field("updatetime","1350327958")
						.endObject())
			        );
		}catch(Exception e){
			e.printStackTrace();
		}
		bulkRequest.execute().actionGet();   
 
 
		return bulkRequest.numberOfActions();
	}

创建查询:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
	public static void query(String query,String indexName,String indexType){
		Client client = ESServiceSingleton2.getTransportClient();
 
		SearchResponse response = client.prepareSearch(indexName)
		        .setTypes(indexType)
		        //.setQuery(getQueryBuilder(query))
		        .setQuery(new CustomScoreQueryBuilder(getQueryBuilder(query)).script(
				"long x=Long.parseLong(doc['updatetime'].value);" +
		        "x=x/86400l;"+
			"_score=_score+sqrt(yy-x)"	
				).param("yy", System.currentTimeMillis()/1000l/86400l))
 
		        .addFields("id","title","updatetime")
		        .setFrom(0).setSize(60).setExplain(true)
		        .addHighlightedField("title")
                .setHighlighterEncoder("UTF-8")
                .setHighlighterPreTags("<em>")
                .setHighlighterPostTags("</em>")
		        .execute()
		        .actionGet();
 
 
		 Float usetime = response.getTookInMillis()/1000f;
	      // 命中记录数
	      Long hits = response.getHits().totalHits();
	      System.out.println("usetime:"+usetime+"  hits:"+hits);
	      for (SearchHit hit : response.getHits()) {
	    	  Float score = hit.getScore();
	          // 文章id
	          Integer id = Integer.parseInt(hit.getFields().get("id").value().toString());
	          String title = hit.getHighlightFields().containsKey("title")?hit.getHighlightFields().get("title").getFragments()[0].toString():hit.getFields().get("title").value().toString();
	          Long updatetime = Long.parseLong(hit.getFields().get("updatetime").value().toString());
	          System.out.println("the record id:"+id+" title: "+title+" updatetime:"+updatetime+"  score:"+score);
	      }
	}

获取querybuilder

1
2
3
4
5
	public static QueryBuilder getQueryBuilder(String query){
		QueryStringQueryBuilder qsqb=new QueryStringQueryBuilder(query);
		qsqb.analyzer("ik").field("title");
	        return qsqb;
	}

主函数:

1
2
3
4
5
6
7
8
9
10
11
public class IndexTest {
	public static void main(String[] args){
		Client client = ESServiceSingleton2.getTransportClient();
		client.admin().indices().prepareDelete("test").execute().actionGet();
		createIndex("test", "xq");
		addIndex("test", "xq");
		client.admin().indices().prepareRefresh().execute().actionGet();
		query("北","test", "xq");
		client.close();
	}
}

customScoreQuery 的script 采用的是mvel的语法。mvel采用了类似java的语法。更多详细资料可参考:
http://blog.csdn.net/fhm727/article/details/6543152

获取java client可参考:http://www.chepoo.com/elasticsearch-java-client-demo.html

customScoreQuery 的script的函数支持可参考:
http://www.elasticsearch.org/guide/reference/modules/scripting/

customScoreQuery 的语法可参考:
http://www.elasticsearch.org/guide/reference/query-dsl/custom-score-query/
http://www.elasticsearch.org/guide/reference/query-dsl/custom-boost-factor-query/

本文固定链接: http://www.chepoo.com/elasticsearch-custom-score-query-demo.html | IT技术精华网

elasticsearch customScoreQuery 实例:等您坐沙发呢!

发表评论