forked from pelias/api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfidenceScoreFallback.js
239 lines (212 loc) · 5.87 KB
/
confidenceScoreFallback.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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
/**
*
* Basic confidence score should be computed and returned for each item in the results.
* The score should range between 0-1, and take into consideration as many factors as possible.
*
* Some factors to consider:
*
* - number of results from ES
* - fallback status (aka layer match between expected and actual)
*/
const _ = require('lodash');
const logger = require('pelias-logger').get('api');
const Debug = require('../helper/debug');
const debugLog = new Debug('middleware:confidenceScoreFallback');
function setup() {
return computeScores;
}
function computeScores(req, res, next) {
// do nothing if no result data set or if the query is not of the fallback variety
// later add disambiguation to this list
if (_.isUndefined(req.clean) || _.isUndefined(res) ||
_.isUndefined(res.data) || _.isUndefined(res.meta)) {
return next();
}
if (['search_fallback', 'address_search_with_ids', 'structured'].includes(res.meta.queryType)) {
return next();
}
// loop through data items and determine confidence scores
res.data = res.data.map(computeConfidenceScore.bind(null, req));
next();
}
/**
* Check all types of things to determine how confident we are that this result
* is correct.
*
* @param {object} req
* @param {object} hit
* @returns {object}
*/
function computeConfidenceScore(req, hit) {
// if parsed text doesn't exist, which it never should, just assign a low confidence and move on
if (!req.clean.hasOwnProperty('parsed_text')) {
hit.confidence = 0.1;
hit.match_type = 'unknown';
return hit;
}
// start with a confidence level of 1 because we trust ES queries to be accurate
hit.confidence = 1.0;
// in the case of fallback there might be deductions
hit.confidence *= checkFallbackLevel(req, hit);
// truncate the precision
hit.confidence = Number((hit.confidence).toFixed(3));
return hit;
}
function checkFallbackLevel(req, hit) {
if (checkFallbackOccurred(req, hit)) {
hit.match_type = 'fallback';
// if we know a fallback occurred, deduct points based on layer granularity
switch (hit.layer) {
case 'venue':
return 0.8;
case 'address':
return 0.8;
case 'street':
return 0.8;
case 'postalcode':
return 0.8;
case 'localadmin':
case 'locality':
case 'borough':
case 'neighbourhood':
return 0.6;
case 'macrocounty':
case 'county':
return 0.4;
case 'region':
return 0.3;
case 'country':
case 'dependency':
case 'macroregion':
return 0.1;
default:
return 0.1;
}
}
hit.match_type = 'exact';
return 1.0;
}
/**
* In parsed_text we might find any of the following properties:
* query
* number
* street
* neighbourhood
* borough
* city
* county
* state
* postalcode
* country
*
* They do not map 1:1 to our layers so the following somewhat complicated
* mapping structure is needed to set clear rules for comparing what was requested
* by the query and what has been received as a result to determine if a fallback occurred.
*/
const fallbackRules = [
{
name: 'venue',
notSet: [],
set: ['query'],
expectedLayers: ['venue']
},
{
name: 'address',
notSet: ['query'],
set: ['housenumber', 'street'],
expectedLayers: ['address']
},
{
name: 'street',
notSet: ['query', 'housenumber'],
set: ['street'],
expectedLayers: ['street']
},
{
name: 'postalcode',
notSet: ['query', 'housenumber', 'street'],
set: ['postalcode'],
expectedLayers: ['postalcode']
},
{
name: 'neighbourhood',
notSet: ['query', 'housenumber', 'street', 'postalcode'],
set: ['neighbourhood'],
expectedLayers: ['neighbourhood']
},
{
name: 'borough',
notSet: ['query', 'housenumber', 'street', 'postalcode', 'neighbourhood'],
set: ['borough'],
expectedLayers: ['borough']
},
{
name: 'city',
notSet: ['query', 'housenumber', 'street', 'postalcode', 'neighbourhood', 'borough'],
set: ['city'],
expectedLayers: ['borough', 'locality', 'localadmin']
},
{
name: 'county',
notSet: ['query', 'housenumber', 'street', 'postalcode', 'neighbourhood', 'borough', 'city'],
set: ['county'],
expectedLayers: ['county']
},
{
name: 'state',
notSet: ['query', 'housenumber', 'street', 'postalcode', 'neighbourhood', 'borough', 'city', 'county'],
set: ['state'],
expectedLayers: ['region']
},
{
name: 'country',
notSet: ['query', 'housenumber', 'street', 'postalcode', 'neighbourhood', 'borough', 'city', 'county', 'state'],
set: ['country'],
expectedLayers: ['country']
}
];
function checkFallbackOccurred(req, hit) {
// short-circuit after finding the first fallback scenario
const res = _.find(fallbackRules, (rule) => {
return (
// verify that more granular properties are not set
notSet(req.clean.parsed_text, rule.notSet) &&
// verify that expected property is set
areSet(req.clean.parsed_text, rule.set) &&
// verify that expected layer(s) was not returned
rule.expectedLayers.indexOf(hit.layer) === -1
);
});
// see: https://github.com/pelias/api/pull/1436
if (Debug.isEnabled(req) && res) {
if (!_.isArray(hit.debug)) { hit.debug = []; }
hit.debug.push({
'middleware:confidenceScoreFallback': {
'fallback rule matched': res
}
});
}
return !!res;
}
function notSet(parsed_text, notSet) {
if (notSet.length === 0) {
return true;
}
return (
_.every(notSet, (prop) => {
return !_.get(parsed_text, prop, false);
})
);
}
function areSet(parsed_text, areSet) {
if (areSet.length === 0) {
logger.warn('Expected properties in fallbackRules should never be empty');
return true;
}
return (
_.every(areSet, (prop) => {
return _.get(parsed_text, prop, false);
})
);
}
module.exports = setup;