如何在kademi中按索引类型过滤搜索结果?
问题描述:
这是我的代码片段,用于从搜索应用程序中使用SearchManager API搜索kademi网站的个人资料,博客和内容。如何在kademi中按索引类型过滤搜索结果?
keyword = params['q'];
var json = {
"query": {
"match": {"_all":keyword}
},
"highlight": {
"fields" : {
"*" : {},
"content" : {
"type" : "plain"
}
}
}
};
var indexes = ["profile", "bran-103166797", "blogs-103166797"]; // profile, content, blog
var sm = applications.search.searchManager;
var result = sm.search(JSON.stringify(json), indexes);
如果你看到下面我的截图,有索引的名字=轮廓几个指数型。我只想从index type = profile
和index name = profile
中获取数据。
答
有一些改动,你应该让 首先,而不是直接命名的指标(如糠103166797),你应该让生成正确的名称使用AppIndexers。否则,当您发布网站的搜索仍然会索引旧版本的新版本:
var sm = applications.search.searchManager;
var indexers = sm.appIndexers;
var profileIndexer = indexers.profile;
var contentIndexer = indexers.content;
然后你就可以使用SearchManager的的prepareSearch方法,它可以让您直接操纵搜索构建:
log.info("using indexers {} {}", profileIndexer, contentIndexer);
var builder = sm.prepareSearch(profileIndexer, contentIndexer);
builder.setSource(JSON.stringify(json));
builder.setTypes("profile", "html");
然后,您可以使用elasticsearch API方法执行搜索查询。请注意,在这个示例中,我使用内联js脚本而不是js控制器,所以我需要将结果设置为请求属性,以便模板可以访问它。
var result = builder.execute().actionGet();
log.info("result {}", result);
http.request.attributes.result = result;
这里是一个完整的样例: http://docs.kademi.co/howtos/devs/advanced-search-pages-with-the-searchmanager-api.html
而在这例子模板的来源是在这里:
<html>
<head>
<title>search page</title>
</head>
<body>
#script()
<script>
var keyword = http.request.params.q;
var json = {
"query": {
"match": {"_all":keyword}
},
"fields" : ["nickName", "title"],
"highlight": {
"fields" : {
"*" : {},
"content" : {
"type" : "plain"
}
}
}
};
var sm = applications.search.searchManager;
var indexers = sm.appIndexers;
var profileIndexer = indexers.profile;
var contentIndexer = indexers.content;
log.info("using indexers {} {}", profileIndexer, contentIndexer);
var builder = sm.prepareSearch(profileIndexer, contentIndexer);
builder.setSource(JSON.stringify(json));
builder.setTypes("profile", "html");
var result = builder.execute().actionGet();
log.info("result {}", result);
http.request.attributes.result = result; // make available to templating
</script>
#end
<div class="container">
<h1>Search</h1>
<p class="pull-right lead">Showing $request.attributes.result.hits.hits.size() of $request.attributes.result.hits.totalHits hits</p>
<table class="table table-striped">
#foreach($hit in $request.attributes.result.hits)
<tr>
<td>
$!hit.fields.nickName.value $!hit.fields.title.value
</td>
<td>$hit.type</td>
</tr>
#end
</table>
</div>
<!-- for debugging, just display the search result as json -->
<pre>$request.attributes.result</pre>
</body>
以上
我没有说明确,但该方法允许设置文档类型匹配 – brad