-
Notifications
You must be signed in to change notification settings - Fork 45
/
entitySearch.js
203 lines (195 loc) · 8.16 KB
/
entitySearch.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
'use strict';
const util = require('util');
const os = require("os");
const async = require('async');
const Search = require('azure-cognitiveservices-search');
const CognitiveServicesCredentials = require('ms-rest-azure').CognitiveServicesCredentials;
let subscriptionKey = process.env['BING_ENTITY_SEARCH_SUBSCRIPTION_KEY']
// Add your Bing Entity Search subscription key to your environment variables.
if (subscriptionKey == null || subscriptionKey == "" || subscriptionKey == undefined) {
throw new Error('Set/export your subscription key as an environment variable.');
}
///////////////////////////////////////////
// Entrypoint for sample script //
///////////////////////////////////////////
let credentials = new CognitiveServicesCredentials(subscriptionKey);
let entitySearchApiClient = new Search.EntitySearchAPIClient(credentials);
let entityModels = entitySearchApiClient.models;
function sample() {
async.series([
async function () {
console.log("1. This will look up a single entity (Alan Turing) and print out a short description about them.");
let result;
try {
result = await entitySearchApiClient.entitiesOperations.search("Alan Turing");
} catch (err) {
if (err instanceof entityModels.ErrorResponse) {
console.log("Encountered exception. " + err.message);
}
}
if (((result.entities || {}).value || {}).length > 0) {
// find the entity that represents the dominant one
let mainEntity = result.entities.value.find(
(thing) => thing.entityPresentationInfo.entityScenario == "DominantEntity"
);
if (mainEntity) {
console.log("Searched for \"Alan Turing\" and found a dominant entity with this description:");
console.log(mainEntity.description);
}
else {
console.log("Couldn't find main entity Alan Turing!");
}
}
else {
console.log("Didn't see any data..");
}
},
async function () {
console.log(os.EOL);
console.log("2. This will handle disambiguation results for an ambiguous query (William Gates).");
let result;
try {
result = await entitySearchApiClient.entitiesOperations.search("William Gates");
} catch (err) {
if (err instanceof entityModels.ErrorResponse) {
console.log("Encountered exception. " + err.message);
}
}
if (((result.entities || {}).value || {}).length > 0) {
// find the entity that represents the dominant one
let mainEntity = result.entities.value.find(
(thing) => thing.entityPresentationInfo.entityScenario == "DominantEntity"
);
let disambigEntities = result.entities.value.filter(
(thing) => thing.entityPresentationInfo.entityScenario == "DisambiguationItem"
)
if (mainEntity) {
console.log(util.format("Searched for \"William Gates\" and found a dominant entity with type hint \"%s\" " +
"with this description:", mainEntity.entityPresentationInfo.entityTypeHints));
console.log(mainEntity.description);
}
else {
console.log("Couldn't find a reliable dominant entity for William Gates!");
}
if (disambigEntities.length > 0) {
console.log(os.EOL);
console.log("This query is pretty ambiguous and can be referring to multiple things. " +
"Did you mean one of these: ")
let stringBuilder = disambigEntities[0].name + " the " +
disambigEntities[0].entityPresentationInfo.entityTypeDisplayHint;
for (let i = 1; i < disambigEntities.length; i++) {
stringBuilder += ", or " + disambigEntities[i].name + " the " +
disambigEntities[i].entityPresentationInfo.entityTypeDisplayHint;
}
console.log(stringBuilder + "?");
}
else {
console.log("We didn't find any disambiguation items for William Gates, so we must be certain what you're talking about!");
}
}
else {
console.log("Didn't see any data..");
}
},
async function () {
console.log(os.EOL);
console.log("3. This will look up a single business (Microsoft Store Bellevue) and print out its phone number.");
let httpResponse;
try {
httpResponse = await entitySearchApiClient.entitiesOperations.searchWithHttpOperationResponse("Microsoft Store Bellevue");
} catch (err) {
if (err instanceof entityModels.ErrorResponse) {
console.log("Encountered exception. " + err.message);
}
}
let result = JSON.parse(httpResponse.response.body);
if (((result.places || {}).value || {}).length > 0) {
let business = result.places.value[0];
if (business) {
console.log("Searched for \"Microsoft Store Bellevue\" and found a business with this phone number:");
console.log(business.telephone);
}
else {
console.log("Couldn't find a place!");
}
}
else {
console.log("Didn't see any data..");
}
},
async function () {
console.log(os.EOL);
console.log("4. This will look up a list of restaurants (seattle restaurants) and present their names and phone numbers.");
let httpResponse;
try {
httpResponse = await entitySearchApiClient.entitiesOperations.searchWithHttpOperationResponse("seattle restaurants");
} catch (err) {
if (err instanceof entityModels.ErrorResponse) {
console.log("Encountered exception. " + err.message);
}
}
let result = JSON.parse(httpResponse.response.body);
if (((result.places || {}).value || {}).length > 0) {
// get all the list items that relate to this query
let listItems = result.places.value.filter(
(thing) => thing.entityPresentationInfo.entityScenario == "ListItem"
)
if (listItems.length > 0) {
let stringBuilder = "";
for (let i = 0; i < listItems.length; i++) {
let place = listItems[i];
stringBuilder += util.format(", %s (%s)", place.name, place.telephone);
}
console.log("Ok, we found these places: ");
console.log(stringBuilder.slice(1));
}
else {
console.log("Couldn't find any relevant results for \"seattle restaurants\"");
}
}
else {
console.log("Didn't see any data..");
}
},
async function () {
console.log(os.EOL);
console.log("5. This triggers a bad request and shows how to read the error response.");
let result;
try {
result = await entitySearchApiClient.entitiesOperations.search("Alan Turing", { market: "no-ty" });
} catch (err) {
if (err instanceof entityModels.ErrorResponse) {
// The status code of the error should be a good indication of what occurred.
// However, if you'd like more details, you can dig into the response.
// Please note that depending on the type of error, the response schema might be different,
// so you aren't guaranteed a specific error response schema.
console.log(util.format("Exception occurred, status code %s.", err.response.statusCode));
// if you'd like more descriptive information (if available), look at the error body.
if (err.body && err.body.errors.length > 0) {
for (let i = 0; i > err.body.length; i++) {
if (err.body.errors[i].subCode == "ParameterInvalidValue") {
console.log(util.format("Turns out the issue is parameter \"%s\" has an invalid value \"%s\". " +
"Detailed message is \"%s\"", err.body.errors[i].parameter, err.body.errors[i].value, err.body.errors[i].message))
}
}
}
}
}
},
function () {
return new Promise((resolve) => {
console.log("Finished running Entity-Search sample.");
resolve();
})
}
], (err) => {
throw (err);
});
}
sample()
exports.sample = sample;