@natlibfi/melinda-record-matching 2.2.1-alpha.1 → 2.2.1-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/candidate-search/candidate-search-utils.js +58 -0
  2. package/dist/candidate-search/candidate-search-utils.js.map +1 -0
  3. package/dist/candidate-search/index.js +273 -0
  4. package/dist/candidate-search/index.js.map +1 -0
  5. package/dist/candidate-search/index.spec.js +161 -0
  6. package/dist/candidate-search/index.spec.js.map +1 -0
  7. package/dist/candidate-search/query-list/bib.js +252 -0
  8. package/dist/candidate-search/query-list/bib.js.map +1 -0
  9. package/dist/candidate-search/query-list/bib.spec.js +72 -0
  10. package/dist/candidate-search/query-list/bib.spec.js.map +1 -0
  11. package/dist/candidate-search/query-list/index.js +67 -0
  12. package/dist/candidate-search/query-list/index.js.map +1 -0
  13. package/dist/index.js +578 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/index.spec.js +133 -0
  16. package/dist/index.spec.js.map +1 -0
  17. package/dist/match-detection/features/bib/all-source-ids.js +122 -0
  18. package/dist/match-detection/features/bib/all-source-ids.js.map +1 -0
  19. package/dist/match-detection/features/bib/authors.js +120 -0
  20. package/dist/match-detection/features/bib/authors.js.map +1 -0
  21. package/dist/match-detection/features/bib/bibliographic-level.js +42 -0
  22. package/dist/match-detection/features/bib/bibliographic-level.js.map +1 -0
  23. package/dist/match-detection/features/bib/host-component.js +42 -0
  24. package/dist/match-detection/features/bib/host-component.js.map +1 -0
  25. package/dist/match-detection/features/bib/index.js +104 -0
  26. package/dist/match-detection/features/bib/index.js.map +1 -0
  27. package/dist/match-detection/features/bib/index.spec.js +97 -0
  28. package/dist/match-detection/features/bib/index.spec.js.map +1 -0
  29. package/dist/match-detection/features/bib/isbn.js +55 -0
  30. package/dist/match-detection/features/bib/isbn.js.map +1 -0
  31. package/dist/match-detection/features/bib/issn.js +55 -0
  32. package/dist/match-detection/features/bib/issn.js.map +1 -0
  33. package/dist/match-detection/features/bib/language.js +113 -0
  34. package/dist/match-detection/features/bib/language.js.map +1 -0
  35. package/dist/match-detection/features/bib/melinda-id.js +52 -0
  36. package/dist/match-detection/features/bib/melinda-id.js.map +1 -0
  37. package/dist/match-detection/features/bib/melinda-identifier-factory.js +100 -0
  38. package/dist/match-detection/features/bib/melinda-identifier-factory.js.map +1 -0
  39. package/dist/match-detection/features/bib/other-standard-identifier.js +55 -0
  40. package/dist/match-detection/features/bib/other-standard-identifier.js.map +1 -0
  41. package/dist/match-detection/features/bib/publication-time.js +51 -0
  42. package/dist/match-detection/features/bib/publication-time.js.map +1 -0
  43. package/dist/match-detection/features/bib/record-type.js +43 -0
  44. package/dist/match-detection/features/bib/record-type.js.map +1 -0
  45. package/dist/match-detection/features/bib/standard-identifier-factory.js +127 -0
  46. package/dist/match-detection/features/bib/standard-identifier-factory.js.map +1 -0
  47. package/dist/match-detection/features/bib/title.js +95 -0
  48. package/dist/match-detection/features/bib/title.js.map +1 -0
  49. package/dist/match-detection/features/index.js +15 -0
  50. package/dist/match-detection/features/index.js.map +1 -0
  51. package/dist/match-detection/index.js +184 -0
  52. package/dist/match-detection/index.js.map +1 -0
  53. package/dist/match-detection/index.spec.js +99 -0
  54. package/dist/match-detection/index.spec.js.map +1 -0
  55. package/dist/matching-utils.js +104 -0
  56. package/dist/matching-utils.js.map +1 -0
  57. package/package.json +2 -1
  58. package/src/candidate-search/query-list/bib.js +19 -18
  59. package/src/candidate-search/query-list/index.js +1 -1
  60. package/src/match-detection/features/bib/authors.js +5 -2
  61. package/src/match-detection/features/bib/language.js +2 -2
  62. package/src/match-detection/features/bib/publication-time.js +8 -3
  63. package/src/match-detection/features/bib/record-type.js +2 -0
  64. package/src/match-detection/features/bib/standard-identifier-factory.js +4 -3
  65. package/src/match-detection/features/bib/title.js +6 -4
  66. package/src/matching-utils.js +13 -4
package/dist/index.js ADDED
@@ -0,0 +1,578 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.matchDetection = exports.default = exports.candidateSearch = void 0;
7
+
8
+ var _debug = _interopRequireDefault(require("debug"));
9
+
10
+ var candidateSearch = _interopRequireWildcard(require("./candidate-search"));
11
+
12
+ exports.candidateSearch = candidateSearch;
13
+
14
+ var matchDetection = _interopRequireWildcard(require("./match-detection"));
15
+
16
+ exports.matchDetection = matchDetection;
17
+
18
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
19
+
20
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
21
+
22
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
23
+
24
+ /**
25
+ *
26
+ * @licstart The following is the entire license notice for the JavaScript code in this file.
27
+ *
28
+ * Melinda record matching modules for Javascript
29
+ *
30
+ * Copyright (C) 2020-2022 University Of Helsinki (The National Library Of Finland)
31
+ *
32
+ * This file is part of melinda-record-matching-js
33
+ *
34
+ * melinda-record-matching-js program is free software: you can redistribute it and/or modify
35
+ * it under the terms of the GNU Lesser General Public License as
36
+ * published by the Free Software Foundation, either version 3 of the
37
+ * License, or (at your option) any later version.
38
+ *
39
+ * melinda-record-matching-js is distributed in the hope that it will be useful,
40
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
41
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
42
+ * GNU Lesser General Public License for more details.
43
+ *
44
+ * You should have received a copy of the GNU Affero General Public License
45
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
46
+ *
47
+ * @licend The above is the entire license notice
48
+ * for the JavaScript code in this file.
49
+ *
50
+ */
51
+ //import inspect from 'util';
52
+ var _default = ({
53
+ detection: detectionOptions,
54
+ search: searchOptions,
55
+ maxMatches = 1,
56
+ maxCandidates = 25,
57
+ returnStrategy = false,
58
+ returnQuery = false,
59
+ returnNonMatches = false,
60
+ returnFailures = false
61
+ }) => {
62
+ const debug = (0, _debug.default)('@natlibfi/melinda-record-matching:index');
63
+ const debugData = debug.extend('data');
64
+ debugData(`DetectionOptions: ${JSON.stringify(detectionOptions)}`);
65
+ debugData(`SearchOptions: ${JSON.stringify(searchOptions)}`);
66
+ debugData(`MaxMatches: ${JSON.stringify(maxMatches)}`);
67
+ debugData(`MaxCandidates: ${JSON.stringify(maxCandidates)}`);
68
+ debugData(`ReturnStrategy: ${JSON.stringify(returnStrategy)}`);
69
+ debugData(`ReturnQuery: ${JSON.stringify(returnQuery)}`);
70
+ debugData(`ReturnNonMatches: ${JSON.stringify(returnNonMatches)}`);
71
+ debugData(`ReturnFailures: ${JSON.stringify(returnFailures)}`);
72
+ const detect = (0, matchDetection.default)(detectionOptions, returnStrategy);
73
+ return record => {
74
+ const search = (0, candidateSearch.default)({ ...searchOptions,
75
+ record,
76
+ maxCandidates
77
+ });
78
+ return iterate({}); // candidateCount : amount of candidate records retrived from SRU for matching, NOT including current record set
79
+ // matches : candidates that have been detected as matches by current matcher job
80
+ // nonMatches : candidates that have been detected as non-matches by current matcher job (only if returnNonMatches is 'true')
81
+ // duplicateCount : amount of candidate records that were retrieved from the SRU but not handled further because they were already found in the matches/nonMatches
82
+ // state.totalRecords : amount of candidate records available to the current query (undefined, if there was no queries left)
83
+ // state.query : current query (undefined if there was no queries left)
84
+ // state.searchCounter : sequence for current search for current query (undefined, if there we no queries left)
85
+ // state.queryCandidateCounter: amount of candidate records retrieved from SRU for matching for current query, including the current record set (undefined if there were no queries left)
86
+ // state.queriesLeft : amount of queries left
87
+ // state.queryCounter : sequence for current query
88
+ // state.maxedQueries : queries that resulted in more than serverMaxResults hits
89
+
90
+ async function iterate({
91
+ initialState = {},
92
+ matches = [],
93
+ candidateCount = 0,
94
+ nonMatches = [],
95
+ duplicateCount = 0,
96
+ nonMatchCount = 0,
97
+ conversionFailures = [],
98
+ matchErrors = []
99
+ }) {
100
+ debugData(`Starting next matcher iteration.`);
101
+ const {
102
+ records,
103
+ failures,
104
+ ...state
105
+ } = await search(initialState);
106
+ debugData(`Current state: ${JSON.stringify(state)}, matches: ${matches.length}, candidateCount: ${candidateCount}, nonMatches: ${nonMatches.length}, nonMatchCount: ${nonMatchCount}, conversionFailures: ${conversionFailures}, matchErrors: ${matchErrors.length}`);
107
+ const recordSetSize = records.length;
108
+ const failureSetSize = failures.length;
109
+ const newCandidateCount = candidateCount + recordSetSize + failureSetSize;
110
+ const newConversionFailures = conversionFailures.concat(failures);
111
+ debugData(`Failures: ${failures.length}, ConversionFailures: ${conversionFailures.length}, NewConversionFailures: ${newConversionFailures.length}`);
112
+
113
+ if (recordSetSize > 0) {
114
+ return handleRecordSet();
115
+ }
116
+
117
+ if (state.queriesLeft > 0) {
118
+ debug(`Empty record set ${state.searchCounter} for ${state.query}, but there are ${state.queriesLeft} queries left`);
119
+ return iterate({
120
+ initialState: state,
121
+ matches,
122
+ candidateCount: newCandidateCount,
123
+ nonMatches,
124
+ nonMatchCount,
125
+ duplicateCount,
126
+ conversionFailures: newConversionFailures,
127
+ matchErrors
128
+ });
129
+ }
130
+
131
+ debug(`No (more) candidate records to check, no more queries left, matches: ${matches.length}`);
132
+ return returnResult({
133
+ matches,
134
+ state,
135
+ stopReason: '',
136
+ nonMatches,
137
+ nonMatchCount,
138
+ candidateCount: newCandidateCount,
139
+ duplicateCount,
140
+ conversionFailures: newConversionFailures,
141
+ matchErrors
142
+ });
143
+
144
+ function handleRecordSet() {
145
+ debug(`Checking record set of ${recordSetSize} candidate records for possible matches, found by ${state.searchCounter} search for ${state.query}`);
146
+ const matchResult = iterateRecords({
147
+ records,
148
+ recordSetSize,
149
+ maxMatches,
150
+ matches,
151
+ nonMatches,
152
+ nonMatchCount
153
+ });
154
+ const newDuplicateCount = duplicateCount + matchResult.duplicateCount;
155
+ const newNonMatchCount = nonMatchCount + matchResult.nonMatchCount;
156
+ const {
157
+ newMatches,
158
+ newNonMatches,
159
+ newMatchErrors
160
+ } = handleMatchResult(matchResult, matches, nonMatches, matchErrors);
161
+
162
+ if (maxMatchesFound({
163
+ matches: newMatches,
164
+ maxMatches
165
+ })) {
166
+ return returnResult({
167
+ matches: newMatches,
168
+ state,
169
+ stopReason: 'maxMatches',
170
+ nonMatches: newNonMatches,
171
+ duplicateCount: newDuplicateCount,
172
+ candidateCount: newCandidateCount,
173
+ nonMatchCount: newNonMatchCount,
174
+ conversionFailures: newConversionFailures,
175
+ matchErrors: newMatchErrors
176
+ });
177
+ }
178
+
179
+ if (maxCandidatesRetrieved(newCandidateCount, maxCandidates)) {
180
+ return returnResult({
181
+ matches: newMatches,
182
+ state,
183
+ stopReason: 'maxCandidates',
184
+ nonMatches: newNonMatches,
185
+ duplicateCount: newDuplicateCount,
186
+ candidateCount: newCandidateCount,
187
+ nonMatchCount: newNonMatchCount,
188
+ conversionFailures: newConversionFailures,
189
+ matchErrors: newMatchErrors
190
+ });
191
+ }
192
+
193
+ return iterate({
194
+ initialState: state,
195
+ matches: newMatches,
196
+ candidateCount: newCandidateCount,
197
+ nonMatches: newNonMatches,
198
+ duplicateCount: newDuplicateCount,
199
+ nonMatchCount: newNonMatchCount,
200
+ conversionFailures: newConversionFailures,
201
+ matchErrors: newMatchErrors
202
+ });
203
+ }
204
+
205
+ function handleMatchResult(matchResult, matches, nonMatches, matchErrors) {
206
+ debugData(`- Amount of new matches from record set: ${matchResult.matches.length}`); // eslint-disable-next-line functional/no-conditional-statement
207
+
208
+ if (returnNonMatches) {
209
+ debugData(`- Amount of new nonMatches from record set: ${matchResult.nonMatches.length}`);
210
+ }
211
+
212
+ const newMatches = matches.concat(returnQuery ? addQuery(matchResult.matches) : matchResult.matches);
213
+ const newNonMatches = returnNonMatches ? nonMatches.concat(returnQuery ? addQuery(matchResult.nonMatches) : matchResult.nonMatches) : [];
214
+ const newMatchErrors = matchErrors.concat(matchResult.matchErrors);
215
+ debugData(`- Total amount of matches: ${newMatches.length}`); // eslint-disable-next-line functional/no-conditional-statement
216
+
217
+ if (returnNonMatches) {
218
+ debugData(`- Total amount of nonMatches: ${newNonMatches.length}`);
219
+ }
220
+
221
+ debugData(`MatchResult: ${JSON.stringify(matchResult)}`);
222
+ debugData(`Old matchErrors: ${JSON.stringify(matchErrors)}, matchErrors from matchResult: ${JSON.stringify(matchResult.matchErrors)}, New matchErrors: ${JSON.stringify(newMatchErrors)}`);
223
+ debugData(`- Total amount of matchErrors: ${newMatchErrors.length}`);
224
+ return {
225
+ newMatches,
226
+ newNonMatches,
227
+ newMatchErrors
228
+ };
229
+ }
230
+
231
+ function addQuery(matches) {
232
+ debugData(`Adding query ${state.query} to matches`);
233
+ return matches.map(match => ({ ...match,
234
+ matchQuery: state.query
235
+ }));
236
+ }
237
+
238
+ function maxCandidatesRetrieved(candidateCount, maxCandidates) {
239
+ debugData(`Total amount of candidate records retrieved: ${newCandidateCount} (max: ${maxCandidates})`);
240
+
241
+ if (maxCandidates && candidateCount >= maxCandidates) {
242
+ debug(`Stopped matching because maximum number of candidate records ${candidateCount} / ${maxCandidates} have been retrieved`);
243
+ return true;
244
+ }
245
+ }
246
+ } // matches : array of matching candidate records
247
+ // nonMatches : array of nonMatching candidate records (if returnNonMatches option is true, otherwise empty array)
248
+ // - candidate.id
249
+ // - candidate.record
250
+ // - probability
251
+ // - strategy (if returnStrategy option is true)
252
+ // - treshold (if returnStrategy option is true)
253
+ // - matchQuery (if returnQuery option is true)
254
+ // failures: array of conversionFailures from candidate-search and matchErrors from matchDetection in error format {status, payload: {message, id}} if returnFailures is true
255
+ // we could have here also returnRecords/returnMatchRecords/returnNonMatchRecord options that could be turned false for not to return actual record data
256
+ // matchStatus.status: boolean, true if matcher retrieved and handled all found candidate records, false if it did not
257
+ // matchStatus.stopReason: string ('maxMatches','maxCandidates','maxedQueries','conversionFailures', empty string/undefined), reason for stopping retrieving or handling the candidate records
258
+ // - only one stopReason is returned (if there would be several possible stopReasons, stopReason is picked in the above order)
259
+ // - currently stopReason can be non-empty also in cases where status is true, if matcher hit the stop reason when handling the last available candidate record
260
+
261
+
262
+ function returnResult({
263
+ matches,
264
+ state,
265
+ stopReason,
266
+ nonMatches,
267
+ duplicateCount,
268
+ candidateCount,
269
+ nonMatchCount,
270
+ conversionFailures,
271
+ matchErrors
272
+ }) {
273
+ const conversionFailureCount = conversionFailures.length;
274
+ const matchErrorCount = matchErrors.length;
275
+ checkCounts({
276
+ matches,
277
+ nonMatches,
278
+ candidateCount,
279
+ duplicateCount,
280
+ nonMatchCount,
281
+ conversionFailureCount,
282
+ matchErrorCount
283
+ });
284
+ const matchStatus = getMatchState(state, stopReason, conversionFailureCount, matchErrorCount); // add nonMatches to result only if returnNonMatches is 'true', otherwise nonMatches have not been gathered
285
+
286
+ const matchesResult = returnNonMatches ? {
287
+ matches,
288
+ matchStatus,
289
+ nonMatches
290
+ } : {
291
+ matches,
292
+ matchStatus
293
+ };
294
+ const failures = [...conversionFailures, ...matchErrors];
295
+ const result = returnFailures ? { ...matchesResult,
296
+ conversionFailures: failures
297
+ } : matchesResult;
298
+ debugData(`ReturnFailures ${returnFailures}`);
299
+ debugData(`${JSON.stringify(result)}`);
300
+ return result; // note that in cases where the matching has been stopped because of maxMatches checkCounts won't (in most cases) match
301
+
302
+ function checkCounts({
303
+ matches,
304
+ nonMatches,
305
+ candidateCount,
306
+ duplicateCount,
307
+ nonMatchCount,
308
+ conversionFailureCount,
309
+ matchErrorCount
310
+ }) {
311
+ const matchCount = matches.length;
312
+ debugData(`Return nonMatches: ${returnNonMatches}`);
313
+ const chosenNonMatchCount = returnNonMatches ? nonMatches.length : nonMatchCount;
314
+ const totalHandled = matchCount + chosenNonMatchCount + duplicateCount;
315
+ debug(`candidateCount: ${candidateCount}, matches: ${matchCount}, nonMatches: ${chosenNonMatchCount}, duplicateCount: ${duplicateCount}, conversionFailureCount: ${conversionFailureCount}, matchErrorCount: ${matchErrorCount}`);
316
+ debug(`We got result for ${totalHandled} / ${candidateCount} retrieved candidates`);
317
+
318
+ if (totalHandled !== candidateCount) {
319
+ debug(`WARNING: Missing results for ${candidateCount - totalHandled} candidates`);
320
+ return;
321
+ }
322
+
323
+ return;
324
+ } // eslint-disable-next-line max-statements
325
+
326
+
327
+ function getMatchState(state, stopReason, conversionFailuresCount, matchErrorCount) {
328
+ debugData(`${JSON.stringify(state)}`);
329
+ debug(`We had ${conversionFailuresCount} retrieved candidates that could not be converted.`);
330
+ debug(`We had ${matchErrorCount} retrieved candidates that errored in matchDetection.`);
331
+ debug(`Queries left ${state.queriesLeft}, Searches for current query left: ${state.resultSetOffset && state.resultSetOffset <= state.totalRecords}, non-retrieved records: ${state.totalRecords - state.queryCandidateCounter}, maxedQueries (${state.maxedQueries.length}): ${state.maxedQueries}`);
332
+ debugData(`StopReason: <${stopReason}>`);
333
+ const searchesLeft = state.resultSetOffset && state.resultSetOffset <= state.totalRecords;
334
+ const nonRetrieved = searchesLeft ? state.totalRecords - state.queryCandidateCounter : 0;
335
+ debugData(`nonRetrieved: ${nonRetrieved}`); // matchStatus.stopReason: string ('maxMatches','maxCandidates','maxedQueries','conversionFailures', empty string/undefined), reason for stopping retrieving or handling the candidate records
336
+ // 'maxMatches' and 'maxCandidates' are in stopReason, 'maxedQueries', 'conversionFailures' and 'matchErrors' are created here
337
+
338
+ if (state.queriesLeft > 0 || nonRetrieved > 0 || state.maxedQueries.length > 0 || conversionFailureCount > 0 || matchErrorCount > 0) {
339
+ const maxedQueriesStopReason = state.maxedQueries.length > 0 ? 'maxedQueries' : undefined;
340
+ const conversionFailuresStopReason = conversionFailureCount > 0 ? 'conversionFailures' : undefined;
341
+ const matchErrorsStopReason = matchErrorCount > 0 ? 'matchErrors' : undefined;
342
+ const newStopReason = stopReason === '' || stopReason === undefined ? maxedQueriesStopReason || conversionFailuresStopReason || matchErrorsStopReason : stopReason;
343
+ debugData(`MaxedQueriesStopReason: <${maxedQueriesStopReason}>`);
344
+ debugData(`ConversionFailureStopReason <${conversionFailuresStopReason}>`);
345
+ debugData(`MatchErrorsStopReason <${matchErrorsStopReason}>`);
346
+ debugData(`NewStopReason: <${newStopReason}>`);
347
+ debug(`Match status: false`);
348
+ return {
349
+ status: false,
350
+ stopReason: newStopReason
351
+ };
352
+ }
353
+
354
+ debug(`Match status: true`);
355
+ return {
356
+ status: true,
357
+ stopReason
358
+ };
359
+ }
360
+ } // NOTES:
361
+ // - we could optimize by creating the featureSet for the incoming record once and using it for all database/candidateRecords
362
+ // - if creating the featureSet for the incoming record fails we have an unprocessable entity
363
+ // - if creating the featureSet for a candidate record fails we could skip that candidate - but list the case as a detectionFailure, same as conversionFailures
364
+ // eslint-disable-next-line max-statements
365
+
366
+
367
+ function iterateRecords({
368
+ records,
369
+ recordSetSize,
370
+ maxMatches,
371
+ matches = [],
372
+ nonMatches = [],
373
+ recordMatches = [],
374
+ recordNonMatches = [],
375
+ recordCount = 0,
376
+ recordDuplicateCount = 0,
377
+ recordNonMatchCount = 0,
378
+ recordMatchErrors = []
379
+ }) {
380
+ // recordSetSize : total amount of records in the current record set
381
+ // recordCount : amount of records from the current record set that have been handled
382
+ // maxMatches : setting for maximum amount found by current matcher job before the matcher job is stopped
383
+ // recordDuplicateCount : amount of records from the current record set that are already included in matches/nonMatches results
384
+ // recordNonMatchCount: amount of records from the current record set that are nonMatches (only is returnNonMatches setting is false)
385
+ // records : non-handled records in the current record set
386
+ // matches : found matches in the current matcher job
387
+ // recordMatches : found matches in the current record set
388
+ // recordNonMatches : found nonMatches in the current record set (only if returnNonMatches setting is true)
389
+ // recordMatchErrors: errored matchDetection in the current record set
390
+ const [candidate] = records;
391
+ const newRecordCount = candidate ? recordCount + 1 : recordCount; // The matcher uses same matchDetection strategy for candidates from all candidate-searches -> matchDetection result for the same candidate is always same
392
+ // Exceptions would happen if the candidate would have been updated in the database between candidate searches
393
+ // Note that if returnNonMatches is false, matcher won't remember candidates that didn't match, so they will be matched again everytime they are retrieved by
394
+ // different candidate search queries. Same candidate search query won't have duplicate records.
395
+
396
+ /* We could optimize and detect all retrieved candidates at once
397
+ const candidateRecords = records.map(record => record.record);
398
+ const recordsIsArray = Array.isArray(candidateRecords);
399
+ debug(`records is an array: ${recordsIsArray}`);
400
+ const result = detect(record, candidateRecords);
401
+ debug(`${JSON.stringify(result)}`);
402
+ */
403
+
404
+ if (candidate) {
405
+ // eslint-disable-next-line functional/no-conditional-statement
406
+ if (candidateNotInMatches(matches.concat(nonMatches), candidate)) {
407
+ const {
408
+ record: candidateRecord,
409
+ id: candidateId
410
+ } = candidate;
411
+
412
+ try {
413
+ debug(`Running matchDetection for record ${candidateId} (${newRecordCount}/${recordSetSize})`); // we should handle errors from detection somehow - ie. cases where either record or candidateRecord errors
414
+
415
+ const detectionResult = detect(record, candidateRecord);
416
+ return handleDetectionResult(detectionResult, candidateId, candidateRecord);
417
+ } catch (error) {
418
+ debug(`MatchDetection errored: database record ${candidateId}: ${error}`);
419
+ const matchError = {
420
+ status: 422,
421
+ payload: {
422
+ message: `Matching errored for database record ${candidateId}. ${error.message}.`,
423
+ id: candidateId
424
+ }
425
+ };
426
+ const newRecordMatchErrors = recordMatchErrors.concat(matchError);
427
+ return iterateRecords({
428
+ records: records.slice(1),
429
+ recordSetSize,
430
+ maxMatches,
431
+ matches,
432
+ recordMatches,
433
+ recordCount: newRecordCount,
434
+ recordNonMatches,
435
+ recordDuplicateCount,
436
+ recordNonMatchCount,
437
+ recordMatchErrors: newRecordMatchErrors
438
+ });
439
+ }
440
+ }
441
+
442
+ return iterateRecords({
443
+ records: records.slice(1),
444
+ recordSetSize,
445
+ maxMatches,
446
+ matches,
447
+ recordMatches,
448
+ recordCount: newRecordCount,
449
+ recordNonMatches,
450
+ recordDuplicateCount: recordDuplicateCount + 1,
451
+ recordNonMatchCount,
452
+ recordMatchErrors
453
+ });
454
+ }
455
+
456
+ debug(`No more candidates, record set (${recordCount}/${recordSetSize}) done, ${recordMatches.length} matches found, ${recordDuplicateCount} candidates already handled, ${returnNonMatches ? `${recordNonMatches.length}` : `${recordNonMatchCount}`} nonMatches found.`);
457
+ return {
458
+ matches: recordMatches,
459
+ nonMatches: returnNonMatches ? recordNonMatches : [],
460
+ duplicateCount: recordDuplicateCount,
461
+ nonMatchCount: recordNonMatchCount,
462
+ matchErrors: recordMatchErrors
463
+ };
464
+
465
+ function handleDetectionResult(detectionResult, candidateId, candidateRecord) {
466
+ debugData(`MatchDetection results for ${candidateId} (${newRecordCount}/${recordSetSize}): ${JSON.stringify(detectionResult)}`);
467
+
468
+ if (detectionResult.match || returnNonMatches) {
469
+ debug(`${detectionResult.match ? `Record ${candidateId} (${newRecordCount}/${recordSetSize}) is a match!` : `Record ${candidateId} (${newRecordCount}/${recordSetSize}) is NOT a match!`}`);
470
+ debugData(`Strategy: ${JSON.stringify(detectionResult.strategy)}, Treshold: ${JSON.stringify(detectionResult.treshold)}`);
471
+ const matchResult = {
472
+ probability: detectionResult.probability,
473
+ candidate: {
474
+ id: candidateId,
475
+ record: candidateRecord
476
+ }
477
+ };
478
+ const strategyResult = {
479
+ strategy: detectionResult.strategy,
480
+ treshold: detectionResult.treshold
481
+ };
482
+ const newMatch = returnStrategy ? { ...matchResult,
483
+ ...strategyResult
484
+ } : { ...matchResult
485
+ };
486
+ debugData(`${JSON.stringify(newMatch)}`);
487
+ return handleRecordMatch(detectionResult.match, newMatch);
488
+ }
489
+
490
+ const newRecordNonMatchCount = recordNonMatchCount + 1;
491
+ debugData(`- Total nonMatches after this detection: ${newRecordNonMatchCount}`);
492
+ return iterateRecords({
493
+ records: records.slice(1),
494
+ recordSetSize,
495
+ maxMatches,
496
+ matches,
497
+ recordMatches,
498
+ recordCount: newRecordCount,
499
+ recordNonMatches,
500
+ recordDuplicateCount,
501
+ recordNonMatchCount: newRecordNonMatchCount,
502
+ recordMatchErrors
503
+ });
504
+ }
505
+
506
+ function handleRecordMatch(isMatch, newMatch) {
507
+ const newRecordMatches = isMatch ? recordMatches.concat(newMatch) : recordMatches;
508
+ const newRecordNonMatches = isMatch ? recordNonMatches : recordNonMatches.concat(newMatch);
509
+ const newRecordNonMatchCount = isMatch ? recordNonMatchCount : recordNonMatchCount + 1;
510
+ debugData(`- Total matches after this detection: ${matches.concat(newRecordMatches).length} (max: ${maxMatches})`); // eslint-disable-next-line functional/no-conditional-statement
511
+
512
+ if (returnNonMatches) {
513
+ debugData(`- Total nonMatches after this detection: ${nonMatches.concat(newRecordNonMatches).length}`);
514
+ }
515
+
516
+ debugData(`- Total nonMatchCount after this detection: ${recordNonMatchCount}`);
517
+
518
+ if (maxMatchesFound({
519
+ matches: matches.concat(newRecordMatches),
520
+ maxMatches
521
+ })) {
522
+ debug(`MaxMatches (${maxMatches}) reached, handled candidates in record set: ${newRecordCount} non-handled candidates in record set ${recordSetSize - newRecordCount}`);
523
+ return {
524
+ matches: newRecordMatches,
525
+ nonMatches: returnNonMatches ? newRecordNonMatches : [],
526
+ duplicateCount: recordDuplicateCount,
527
+ nonMatchCount: newRecordNonMatchCount,
528
+ matchErrors: recordMatchErrors
529
+ };
530
+ }
531
+
532
+ return iterateRecords({
533
+ records: records.slice(1),
534
+ recordSetSize,
535
+ maxMatches,
536
+ matches,
537
+ recordMatches: newRecordMatches,
538
+ recordCount: newRecordCount,
539
+ recordNonMatches: returnNonMatches ? newRecordNonMatches : [],
540
+ duplicateCount: recordDuplicateCount,
541
+ recordNonMatchCount: newRecordNonMatchCount,
542
+ matchErrors: recordMatchErrors
543
+ });
544
+ }
545
+
546
+ function candidateNotInMatches(matches, candidate) {
547
+ debug(`Checking that record ${candidate.id} is not already included in ${matches.length} matches/nonMatches`);
548
+ const newCandidateId = candidate.id;
549
+ debugData(`newCandidateId: ${newCandidateId}`);
550
+ const result = matches.find(({
551
+ candidate
552
+ }) => candidate.id === newCandidateId);
553
+ debugData(`Result: ${result}`);
554
+
555
+ if (result) {
556
+ debug(`${candidate.id} was already handled.`);
557
+ return false;
558
+ }
559
+
560
+ debug(`${candidate.id} not found in matches/nonMatches`);
561
+ return true;
562
+ }
563
+ }
564
+
565
+ function maxMatchesFound({
566
+ matches,
567
+ maxMatches
568
+ }) {
569
+ if (maxMatches && matches.length >= maxMatches) {
570
+ debug(`Stopping recordSet iteration: maxMatches (${maxMatches}) for matcher job found.`);
571
+ return true;
572
+ }
573
+ }
574
+ };
575
+ };
576
+
577
+ exports.default = _default;
578
+ //# sourceMappingURL=index.js.map