官网地址:https://www.elastic.co/guide/en/elasticsearch/reference/2.3/query-dsl-mlt-query.html
基于内容的推荐通常是给定一篇文档信息,然后给用户推荐与该文档相识的文档。Lucene的api中有实现查询文章相似度的接口,叫MoreLikeThis。Elasticsearch封装了该接口,通过Elasticsearch的More like this查询接口,我们可以非常方便的实现基于内容的推荐。
先看一个查询请求的json例子:
GET /mychat/mytype/_search
{
"query":{
"more_like_this":{
"fields" : ["ask", "answer"],
"like_text" : "中国" ,
"min_term_freq" : 1,
"max_query_terms" : 12
}
}
}
fields是要匹配的字段,如果不填的话默认是_all字段
like_text是匹配的文本。
除此之外还可以添加下面条件来调节结果
percent_terms_to_match:匹配项(term)的百分比,默认是0.3
min_term_freq:一篇文档中一个词语至少出现次数,小于这个值的词将被忽略,默认是2
max_query_terms:一条查询语句中允许最多查询词语的个数,默认是25
stop_words:设置停止词,匹配时会忽略停止词
min_doc_freq:一个词语最少在多少篇文档中出现,小于这个值的词会将被忽略,默认是无限制
max_doc_freq:一个词语最多在多少篇文档中出现,大于这个值的词会将被忽略,默认是无限制
min_word_len:最小的词语长度,默认是0
max_word_len:最多的词语长度,默认无限制
boost_terms:设置词语权重,默认是1
boost:设置查询权重,默认是1
analyzer:设置使用的分词器,默认是使用该字段指定的分词器
下面介绍下如何用Java api调用,一共有三种调用方式,不过本质上都是一样的,只不过是做了一些不同程度的封装。
- MoreLikeThisRequestBuilder mlt = new MoreLikeThisRequestBuilder(client, "indexName", "indexType", "id");
- mlt.setField("title");//匹配的字段
- SearchResponse response = client.moreLikeThis(mlt.request()).actionGet();
- MoreLikeThisQueryBuilder query = QueryBuilders.moreLikeThisQuery();
- query.boost(1.0f).likeText("xxx").minTermFreq(10);
- MoreLikeThisFieldQueryBuilder query = QueryBuilders.moreLikeThisFieldQuery("fieldNmae");
{
"settings": {
"number_of_shards": 2,
"number_of_replicas": 1
},
"mappings": {
"chat_str": {
"date_detection": false,
"dynamic_templates": [{
"es_string": {
"match": "*",
"match_mapping_type": "string",
"mapping": {
"type": "string",
"index": "analyzed",
"analyzer": "ik_max_word"
}
}
}],
"properties": {
"title": {
"type": "string",
"index": "analyzed",
"analyzer": "ik_max_word"
},
"content": {
"type": "string",
"index": "analyzed",
"analyzer": "ik_max_word"
}
}
}
}
}