forked from microsoft/BotBuilder-Samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
azure-search.js
84 lines (72 loc) · 2.55 KB
/
azure-search.js
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
var util = require('util');
var _ = require('lodash');
var Promise = require('bluebird');
var request = require('request');
function create(serviceName, serviceKey, index) {
// base url
// e.g.: https://realestate.search.windows.net/indexes('listings')/docs/search.post.search?api-version=2015-02-28-Preview
var url = "https://" + serviceName + ".search.windows.net" +
"/indexes('" + index + "')" +
"/docs/search.post.search?api-version=2015-02-28-Preview";
return {
search: function (query) {
return new Promise(function (resolve, reject) {
console.log('AzureSearch.inputQuery:', query);
// create request & azure query
var options = {
url: url,
headers: { 'api-key': serviceKey },
withCredentials: false,
json: true,
body: {
count: false,
facets: query.facets || [],
filter: createFilterParams(query.filters),
queryType: 'simple',
scoringParameters: [],
search: query.searchText,
searchMode: 'all',
skip: (query.pageNumber - 1) * query.pageSize,
top: query.pageSize
}
};
console.log('AzureSearch.query:', options.body);
request.post(options, function (err, httpResponse, azureResponse) {
if (err) {
return reject(err);
}
resolve({
results: azureResponse.value,
facets: getFacets(azureResponse)
});
});
});
}
};
}
// Helpers
function getFacets(azureResponse) {
var rawFacets = azureResponse['@search.facets'];
if (!rawFacets) {
return [];
}
var facets = _.toPairs(rawFacets)
.filter(function (p) { return _.isArray(p[1]); })
.map(function (p) { return { key: p[0], options: p[1] }; });
return facets;
}
function createFilterParams(filters) {
if (!filters || !filters.length) {
return '';
}
return filters.map(function (f) {
return util.format('%s eq \'%s\'', f.key, escapeFilterString(f.value));
}).join(' and ');
}
function escapeFilterString(string) {
return string.replace(/'/g, '\'\'');
}
// Exports
module.exports = {
create: create
};