@natlibfi/melinda-record-matching 4.4.0-alpha.1 → 5.0.0-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 (123) hide show
  1. package/.github/workflows/melinda-node-tests.yml +13 -9
  2. package/LICENSE.txt +21 -165
  3. package/README.md +2 -2
  4. package/dist/candidate-search/candidate-search-utils.js +6 -43
  5. package/dist/candidate-search/candidate-search-utils.js.map +7 -1
  6. package/dist/candidate-search/choose-queries.js +75 -0
  7. package/dist/candidate-search/choose-queries.js.map +7 -0
  8. package/dist/candidate-search/index.js +89 -225
  9. package/dist/candidate-search/index.js.map +7 -1
  10. package/dist/candidate-search/index.test.js +92 -0
  11. package/dist/candidate-search/index.test.js.map +7 -0
  12. package/dist/candidate-search/query-list/bib.js +141 -320
  13. package/dist/candidate-search/query-list/bib.js.map +7 -1
  14. package/dist/candidate-search/query-list/bib.test.js +34 -0
  15. package/dist/candidate-search/query-list/bib.test.js.map +7 -0
  16. package/dist/candidate-search/query-list/component.js +87 -0
  17. package/dist/candidate-search/query-list/component.js.map +7 -0
  18. package/dist/candidate-search/query-list/index.js +39 -52
  19. package/dist/candidate-search/query-list/index.js.map +7 -1
  20. package/dist/cli.js +138 -0
  21. package/dist/cli.js.map +7 -0
  22. package/dist/index.js +87 -462
  23. package/dist/index.js.map +7 -1
  24. package/dist/index.test.js +69 -0
  25. package/dist/index.test.js.map +7 -0
  26. package/dist/match-detection/features/bib/all-source-ids.js +20 -91
  27. package/dist/match-detection/features/bib/all-source-ids.js.map +7 -1
  28. package/dist/match-detection/features/bib/authors.js +20 -76
  29. package/dist/match-detection/features/bib/authors.js.map +7 -1
  30. package/dist/match-detection/features/bib/bibliographic-level.js +4 -40
  31. package/dist/match-detection/features/bib/bibliographic-level.js.map +7 -1
  32. package/dist/match-detection/features/bib/host-component.js +5 -41
  33. package/dist/match-detection/features/bib/host-component.js.map +7 -1
  34. package/dist/match-detection/features/bib/index.js +17 -119
  35. package/dist/match-detection/features/bib/index.js.map +7 -1
  36. package/dist/match-detection/features/bib/index.test.js +40 -0
  37. package/dist/match-detection/features/bib/index.test.js.map +7 -0
  38. package/dist/match-detection/features/bib/isbn.js +13 -69
  39. package/dist/match-detection/features/bib/isbn.js.map +7 -1
  40. package/dist/match-detection/features/bib/issn.js +5 -50
  41. package/dist/match-detection/features/bib/issn.js.map +7 -1
  42. package/dist/match-detection/features/bib/language.js +25 -86
  43. package/dist/match-detection/features/bib/language.js.map +7 -1
  44. package/dist/match-detection/features/bib/media-type.js +12 -64
  45. package/dist/match-detection/features/bib/media-type.js.map +7 -1
  46. package/dist/match-detection/features/bib/melinda-id.js +5 -47
  47. package/dist/match-detection/features/bib/melinda-id.js.map +7 -1
  48. package/dist/match-detection/features/bib/melinda-identifier-factory.js +16 -67
  49. package/dist/match-detection/features/bib/melinda-identifier-factory.js.map +7 -1
  50. package/dist/match-detection/features/bib/other-standard-identifier.js +5 -51
  51. package/dist/match-detection/features/bib/other-standard-identifier.js.map +7 -1
  52. package/dist/match-detection/features/bib/publication-time-allow-cons-years-multi.js +49 -189
  53. package/dist/match-detection/features/bib/publication-time-allow-cons-years-multi.js.map +7 -1
  54. package/dist/match-detection/features/bib/publication-time-allow-cons-years.js +10 -53
  55. package/dist/match-detection/features/bib/publication-time-allow-cons-years.js.map +7 -1
  56. package/dist/match-detection/features/bib/publication-time.js +8 -46
  57. package/dist/match-detection/features/bib/publication-time.js.map +7 -1
  58. package/dist/match-detection/features/bib/record-type.js +4 -43
  59. package/dist/match-detection/features/bib/record-type.js.map +7 -1
  60. package/dist/match-detection/features/bib/standard-identifier-factory.js +47 -163
  61. package/dist/match-detection/features/bib/standard-identifier-factory.js.map +7 -1
  62. package/dist/match-detection/features/bib/title-version-original.js +11 -53
  63. package/dist/match-detection/features/bib/title-version-original.js.map +7 -1
  64. package/dist/match-detection/features/bib/title.js +20 -72
  65. package/dist/match-detection/features/bib/title.js.map +7 -1
  66. package/dist/match-detection/features/index.js +3 -11
  67. package/dist/match-detection/features/index.js.map +7 -1
  68. package/dist/match-detection/index.js +35 -150
  69. package/dist/match-detection/index.js.map +7 -1
  70. package/dist/match-detection/index.test.js +44 -0
  71. package/dist/match-detection/index.test.js.map +7 -0
  72. package/dist/matching-utils.js +38 -102
  73. package/dist/matching-utils.js.map +7 -1
  74. package/eslint.config.js +52 -0
  75. package/example.env +4 -0
  76. package/package.json +29 -78
  77. package/src/candidate-search/candidate-search-utils.js +1 -28
  78. package/src/candidate-search/choose-queries.js +93 -0
  79. package/src/candidate-search/index.js +85 -119
  80. package/src/candidate-search/{index.spec.js → index.test.js} +30 -43
  81. package/src/candidate-search/query-list/bib.js +54 -55
  82. package/src/candidate-search/query-list/bib.test.js +38 -0
  83. package/src/candidate-search/query-list/component.js +127 -0
  84. package/src/candidate-search/query-list/index.js +31 -35
  85. package/src/cli.js +177 -0
  86. package/src/index.js +27 -68
  87. package/src/{index.spec.js → index.test.js} +11 -42
  88. package/src/match-detection/features/bib/all-source-ids.js +2 -29
  89. package/src/match-detection/features/bib/authors.js +5 -30
  90. package/src/match-detection/features/bib/bibliographic-level.js +0 -27
  91. package/src/match-detection/features/bib/host-component.js +0 -27
  92. package/src/match-detection/features/bib/index.js +16 -43
  93. package/src/match-detection/features/bib/index.test.js +52 -0
  94. package/src/match-detection/features/bib/isbn.js +2 -29
  95. package/src/match-detection/features/bib/issn.js +1 -28
  96. package/src/match-detection/features/bib/language.js +5 -32
  97. package/src/match-detection/features/bib/media-type.js +2 -28
  98. package/src/match-detection/features/bib/melinda-id.js +1 -28
  99. package/src/match-detection/features/bib/melinda-identifier-factory.js +5 -32
  100. package/src/match-detection/features/bib/other-standard-identifier.js +1 -28
  101. package/src/match-detection/features/bib/publication-time-allow-cons-years-multi.js +7 -34
  102. package/src/match-detection/features/bib/publication-time-allow-cons-years.js +1 -28
  103. package/src/match-detection/features/bib/publication-time.js +2 -28
  104. package/src/match-detection/features/bib/record-type.js +0 -27
  105. package/src/match-detection/features/bib/standard-identifier-factory.js +1 -28
  106. package/src/match-detection/features/bib/title-version-original.js +2 -28
  107. package/src/match-detection/features/bib/title.js +6 -34
  108. package/src/match-detection/features/index.js +1 -28
  109. package/src/match-detection/index.js +1 -28
  110. package/src/match-detection/{index.spec.js → index.test.js} +9 -35
  111. package/src/matching-utils.js +8 -37
  112. package/dist/candidate-search/index.spec.js +0 -144
  113. package/dist/candidate-search/index.spec.js.map +0 -1
  114. package/dist/candidate-search/query-list/bib.spec.js +0 -64
  115. package/dist/candidate-search/query-list/bib.spec.js.map +0 -1
  116. package/dist/index.spec.js +0 -127
  117. package/dist/index.spec.js.map +0 -1
  118. package/dist/match-detection/features/bib/index.spec.js +0 -93
  119. package/dist/match-detection/features/bib/index.spec.js.map +0 -1
  120. package/dist/match-detection/index.spec.js +0 -91
  121. package/dist/match-detection/index.spec.js.map +0 -1
  122. package/src/candidate-search/query-list/bib.spec.js +0 -54
  123. package/src/match-detection/features/bib/index.spec.js +0 -78
@@ -1,37 +1,10 @@
1
- /**
2
- *
3
- * @licstart The following is the entire license notice for the JavaScript code in this file.
4
- *
5
- * Melinda record matching modules for Javascript
6
- *
7
- * Copyright (C) 2020-2022 University Of Helsinki (The National Library Of Finland)
8
- *
9
- * This file is part of melinda-record-matching-js
10
- *
11
- * melinda-record-matching-js program is free software: you can redistribute it and/or modify
12
- * it under the terms of the GNU Lesser General Public License as
13
- * published by the Free Software Foundation, either version 3 of the
14
- * License, or (at your option) any later version.
15
- *
16
- * melinda-record-matching-js is distributed in the hope that it will be useful,
17
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19
- * GNU Lesser General Public License for more details.
20
- *
21
- * You should have received a copy of the GNU Affero General Public License
22
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
23
- *
24
- * @licend The above is the entire license notice
25
- * for the JavaScript code in this file.
26
- *
27
- */
28
-
29
- import {expect} from 'chai';
1
+ import assert from 'node:assert';
2
+ import {describe} from 'node:test';
30
3
  import {READERS} from '@natlibfi/fixura';
31
4
  import generateTests from '@natlibfi/fixugen-http-client';
32
5
  import {MarcRecord} from '@natlibfi/marc-record';
33
6
  import {Error as MatchingError} from '@natlibfi/melinda-commons';
34
- import createSearchInterface, {CandidateSearchError} from '.';
7
+ import createSearchInterface, {CandidateSearchError} from './index.js';
35
8
  import createDebugLogger from 'debug';
36
9
 
37
10
  const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:test');
@@ -39,13 +12,14 @@ const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-sea
39
12
  describe('candidate-search', () => {
40
13
  generateTests({
41
14
  callback,
42
- path: [__dirname, '..', '..', 'test-fixtures', 'candidate-search', 'index'],
15
+ path: [import.meta.dirname, '..', '..', 'test-fixtures', 'candidate-search', 'index'],
43
16
  recurse: false,
44
17
  fixura: {
45
18
  reader: READERS.JSON
46
19
  }
47
20
  });
48
21
 
22
+ // eslint-disable-next-line max-statements
49
23
  async function callback({getFixture, factoryOptions, searchOptions, expectedFactoryError = false, expectedSearchError = false, enabled = true}) {
50
24
  const url = 'http://foo.bar';
51
25
 
@@ -54,16 +28,31 @@ describe('candidate-search', () => {
54
28
  }
55
29
 
56
30
  if (expectedFactoryError) {
31
+ debug(`We're expecting an error`);
57
32
  if (expectedFactoryError.isCandidateSearchError) {
58
- expect(() => createSearchInterface({...formatFactoryOptions(), url})).to.throw(CandidateSearchError, new RegExp(expectedFactoryError, 'u'));
59
- return;
33
+ try {
34
+ const result = await createSearchInterface({...formatFactoryOptions(), url});
35
+ debug(result);
36
+ } catch (err) {
37
+ assert.equal(err instanceof CandidateSearchError, true);
38
+ assert.match(err.message, new RegExp(expectedFactoryError.message));
39
+ } finally {
40
+ return;
41
+ }
60
42
  }
61
43
 
62
- expect(() => createSearchInterface({...formatFactoryOptions(), url})).to.throw(new RegExp(expectedFactoryError, 'u'));
63
- return;
44
+ try {
45
+ const result = await createSearchInterface({...formatFactoryOptions(), url});
46
+ debug(result);
47
+ } catch (err) {
48
+ assert.equal(err instanceof Error, true);
49
+ assert.match(err.message, new RegExp(expectedFactoryError.message));
50
+ } finally {
51
+ return;
52
+ }
64
53
  }
65
54
 
66
- const search = createSearchInterface({...formatFactoryOptions(), url});
55
+ const {search} = await createSearchInterface({...formatFactoryOptions(), url});
67
56
  await iterate({searchOptions, expectedSearchError});
68
57
 
69
58
  function formatFactoryOptions() {
@@ -79,30 +68,29 @@ describe('candidate-search', () => {
79
68
  async function iterate({searchOptions, expectedSearchError, expectedErrorStatus, count = 1}) {
80
69
  const expectedResults = getFixture(`expectedResults${count}.json`);
81
70
 
82
- if (expectedSearchError) { // eslint-disable-line functional/no-conditional-statements
71
+ if (expectedSearchError) {
83
72
  try {
84
73
  await search(searchOptions);
85
74
  throw new Error('Expected an error');
86
75
  } catch (err) {
87
76
  debug(`Got an error: ${err}`);
88
- expect(err).to.be.an('error');
77
+ assert(err instanceof Error);
89
78
  const errorMessage = err instanceof MatchingError ? err.payload.message : err.message;
90
79
  const errorStatus = err instanceof MatchingError ? err.status : undefined;
91
80
  debug(`errorMessage: ${errorMessage}, errorStatus: ${errorStatus}`);
92
- expect(errorMessage).to.match(new RegExp(expectedSearchError, 'u'));
81
+ assert.match(errorMessage, new RegExp(expectedSearchError, 'u'));
93
82
 
94
83
  if (expectedErrorStatus) {
95
- expect(errorStatus).to.be(expectedErrorStatus);
84
+ assert.equal(errorStatus, expectedErrorStatus);
96
85
  return;
97
86
  }
98
87
  return;
99
88
  }
100
89
  }
101
90
 
102
- // eslint-disable-next-line functional/no-conditional-statements
103
91
  if (!expectedSearchError) {
104
92
  const results = await search(searchOptions);
105
- expect(formatResults(results)).to.eql(expectedResults);
93
+ assert.deepStrictEqual(formatResults(results), expectedResults);
106
94
  }
107
95
 
108
96
  function formatResults(results) {
@@ -112,7 +100,6 @@ describe('candidate-search', () => {
112
100
  records: results.records.map(({record, id}) => ({id, record: record.toObject()}))
113
101
  };
114
102
  }
115
-
116
103
  }
117
104
  }
118
105
  });
@@ -1,34 +1,6 @@
1
-
2
- /**
3
- *
4
- * @licstart The following is the entire license notice for the JavaScript code in this file.
5
- *
6
- * Melinda record matching modules for Javascript
7
- *
8
- * Copyright (C) 2020-2022 University Of Helsinki (The National Library Of Finland)
9
- *
10
- * This file is part of melinda-record-matching-js
11
- *
12
- * melinda-record-matching-js program is free software: you can redistribute it and/or modify
13
- * it under the terms of the GNU Lesser General Public License as
14
- * published by the Free Software Foundation, either version 3 of the
15
- * License, or (at your option) any later version.
16
- *
17
- * melinda-record-matching-js is distributed in the hope that it will be useful,
18
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20
- * GNU Lesser General Public License for more details.
21
- *
22
- * You should have received a copy of the GNU Affero General Public License
23
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
24
- *
25
- * @licend The above is the entire license notice
26
- * for the JavaScript code in this file.
27
- *
28
- */
29
1
  import createDebugLogger from 'debug';
30
- import {toQueries} from '../candidate-search-utils';
31
- import {getMelindaIdsF035, validateSidFieldSubfieldCounts, getSubfieldValues, testStringOrNumber} from '../../matching-utils';
2
+ import {toQueries} from '../candidate-search-utils.js';
3
+ import {getMelindaIdsF035, validateSidFieldSubfieldCounts, getSubfieldValues, testStringOrNumber} from '../../matching-utils.js';
32
4
 
33
5
  const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query');
34
6
 
@@ -151,7 +123,13 @@ export function bibMelindaIds(record) {
151
123
  // bibHostComponents returns host id from the first subfield $w of first field f773, see test-fixtures 04 and 05
152
124
  // bibHostComponents should search all 773 $ws for possible host id, but what should it do in case of multiple host ids?
153
125
  export function bibHostComponents(record) {
126
+ const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query:bibHostComponents');
127
+ const debugData = debug.extend('data');
128
+ debug(`Creating queries for hostIds`);
129
+
154
130
  const id = getHostId();
131
+ debugData(`Found id: ${JSON.stringify(id)}`);
132
+
155
133
  return testStringOrNumber(id) ? [`melinda.partsofhost=${id}`] : [];
156
134
 
157
135
  function getHostId() {
@@ -195,18 +173,25 @@ export function bibTitleAuthor(record) {
195
173
  }
196
174
 
197
175
  export function bibTitleAuthorYear(record) {
198
- debug('bibTitleAuthorYear');
176
+ debug('bibTitleAuthorYearAlternates');
199
177
  // We use onlyTitleLength that is longer than our formatted length to
200
178
  // get an author or an publisher always
201
179
 
202
180
  return bibTitleAuthorPublisher({record, onlyTitleLength: 100, addYear: true});
203
181
  }
204
182
 
205
- export function bibTitleAuthorPublisher({record, onlyTitleLength, addYear = false}) {
206
- debug('bibTitleAuthorPublisher');
207
- const title = getTitle();
208
- const booleanStartWords = ['and', 'or', 'nor', 'not'];
183
+ export function bibTitleAuthorYearAlternates(record) {
184
+ debug('bibTitleAuthorYearAlternates');
185
+ // We use onlyTitleLength that is longer than our formatted length to
186
+ // get an author or an publisher always
187
+ const origQueryList = bibTitleAuthorPublisher({record, onlyTitleLength: 100, addYear: true, alternates: true, alternateQueries: []});
188
+ debug(`${JSON.stringify(origQueryList)}`);
189
+ return {queryList: Array.from(origQueryList).reverse(), queryListType: 'alternates'};
190
+ }
209
191
 
192
+ export function bibTitleAuthorPublisher({record, onlyTitleLength, addYear = false, alternates = false, alternateQueries = []}) {
193
+ debug(`bibTitleAuthorPublisher, onlyTitleLength: ${onlyTitleLength}, addYear: ${addYear}, alternates: ${alternates}`);
194
+ const title = getTitle();
210
195
  if (testStringOrNumber(title)) {
211
196
  const formatted = String(title)
212
197
  .replace(/[^\w\s\p{Alphabetic}]/gu, '')
@@ -217,10 +202,10 @@ export function bibTitleAuthorPublisher({record, onlyTitleLength, addYear = fals
217
202
  .trim();
218
203
 
219
204
  // use word search for titles starting with a boolean
220
- const useWordSearch = booleanStartWords.some(word => formatted.toLowerCase().startsWith(word));
205
+ const useWordSearch = checkUseWordSearch(formatted);
221
206
  // Prevent too many matches / SRU crashing by having a minimum length
222
207
  // Note that currently this fails matching if there are no matches from previous matchers
223
- if (formatted.length >= onlyTitleLength) {
208
+ if (formatted.length >= onlyTitleLength && !alternates) {
224
209
  return [`dc.title="${useWordSearch ? '' : '^'}${formatted}*"`];
225
210
  }
226
211
  const queryIsOkAlone = formatted.length >= 5;
@@ -228,45 +213,50 @@ export function bibTitleAuthorPublisher({record, onlyTitleLength, addYear = fals
228
213
  // use word search without ending * also in combination searches to avoid SRU-server crashes [MRA-189]
229
214
  const query = `dc.title="${useWordSearch || !queryIsOkAlone ? '' : '^'}${formatted}${queryIsOkAlone ? '*' : ''}"`;
230
215
  debug(`query: ${query}`);
231
- return addAuthorsToSearch({query, queryIsOkAlone, addYear});
216
+ const newAlternateQueries = alternates ? [...alternateQueries, query] : alternateQueries;
217
+
218
+ return addAuthorsToSearch({query, queryIsOkAlone, addYear, alternates, alternateQueries: newAlternateQueries});
232
219
  }
233
220
 
234
221
  return [];
235
222
 
236
- function addAuthorsToSearch({query, queryIsOkAlone = false, addYear = false}) {
223
+ function addAuthorsToSearch({query, queryIsOkAlone = false, addYear = false, alternates = false, alternateQueries = []}) {
237
224
  debug('addAuthorsToSearch');
238
225
  const [authorQuery] = bibAuthors(record);
239
226
  if (authorQuery !== undefined) {
240
227
  if (addYear) {
241
- return addYearToSearch({query: `${authorQuery} AND ${query}`, queryIsOkAlone: true});
228
+ const newAlternateQueries = alternates ? [...alternateQueries, `${authorQuery} AND ${query}`] : alternateQueries;
229
+ return addYearToSearch({query: `${authorQuery} AND ${query}`, queryIsOkAlone: true, alternates, alternateQueries: newAlternateQueries});
242
230
  }
243
- return [`${authorQuery} AND ${query}`];
231
+ return alternates ? alternateQueries : [`${authorQuery} AND ${query}`];
244
232
  }
245
- return addPublisherToSearch({query, queryIsOkAlone, addYear});
233
+ return addPublisherToSearch({query, queryIsOkAlone, addYear, alternates, alternateQueries});
246
234
  //return [];
247
235
  }
248
236
 
249
- function addPublisherToSearch({query, queryIsOkAlone = false, addYear = false}) {
237
+ function addPublisherToSearch({query, queryIsOkAlone = false, addYear = false, alternates = false, alternateQueries = []}) {
250
238
  const [publisherQuery] = bibPublishers(record);
251
239
  if (publisherQuery !== undefined) {
252
240
  if (addYear) {
253
- return addYearToSearch({query: `${publisherQuery} AND ${query}`, queryIsOkAlone: true});
241
+ const newAlternateQueries = alternates ? [...alternateQueries, `${publisherQuery} AND ${query}`] : alternateQueries;
242
+ return addYearToSearch({query: `${publisherQuery} AND ${query}`, queryIsOkAlone: true, alternates, alternateQueries: newAlternateQueries});
254
243
  }
255
- return [`${publisherQuery} AND ${query}`];
244
+ return alternates ? alternateQueries : [`${publisherQuery} AND ${query}`];
256
245
  }
257
246
  if (queryIsOkAlone && !addYear) {
258
- return [`${query}`];
247
+ return alternates ? alternateQueries : [`${query}`];
259
248
  }
260
- return addYearToSearch({query, queryIsOkAlone});
249
+ return addYearToSearch({query, queryIsOkAlone, alternates, alternateQueries});
261
250
  }
262
251
 
263
- function addYearToSearch({query, queryIsOkAlone = false}) {
252
+ function addYearToSearch({query, queryIsOkAlone = false, alternates = false, alternateQueries = []}) {
264
253
  const [yearQuery] = bibYear(record);
265
254
  if (yearQuery !== undefined) {
266
- return [`${yearQuery} AND ${query}`];
255
+ const newAlternateQueries = alternates ? [...alternateQueries, `${yearQuery} AND ${query}`] : alternateQueries;
256
+ return alternates ? newAlternateQueries : [`${yearQuery} AND ${query}`];
267
257
  }
268
258
  if (queryIsOkAlone) {
269
- return [`${query}`];
259
+ return alternates ? alternateQueries : [`${query}`];
270
260
  }
271
261
  return [];
272
262
  }
@@ -296,8 +286,6 @@ export function bibAuthors(record) {
296
286
  //debugData(record);
297
287
 
298
288
  const author = getAuthor(record);
299
- const booleanStartWords = ['and', 'or', 'nor', 'not'];
300
-
301
289
 
302
290
  if (testStringOrNumber(author)) {
303
291
  const formatted = String(author)
@@ -309,7 +297,7 @@ export function bibAuthors(record) {
309
297
  .trim();
310
298
 
311
299
  // use word search for authors starting with a boolean
312
- const useWordSearch = booleanStartWords.some(word => formatted.toLowerCase().startsWith(word));
300
+ const useWordSearch = checkUseWordSearch(formatted);
313
301
  // Prevent too many matches by having a minimum length
314
302
  debugData(`Author string: ${formatted}`);
315
303
  if (formatted.length >= 5) {
@@ -384,7 +372,6 @@ export function bibYear(record) {
384
372
  const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query:bibYear');
385
373
  const debugData = debug.extend('data');
386
374
  debug(`Creating query for the publishing year`);
387
- debugData(record);
388
375
 
389
376
  const year = getYear(record);
390
377
  if (year) {
@@ -393,11 +380,23 @@ export function bibYear(record) {
393
380
  return [];
394
381
 
395
382
  function getYear(record) {
396
- const value = record.get(/^008$/u)?.[0]?.value || undefined;
383
+ const [f008] = record.get(/^008$/u);
384
+ if (f008 === undefined) {
385
+ debug('f008 missing');
386
+ return false;
387
+ }
388
+
389
+ debugData(`f008: ${JSON.stringify(f008)}`);
390
+ const {value} = f008;
397
391
  return testStringOrNumber(value) ? String(value).slice(7, 11) : undefined;
398
392
  }
399
393
  }
400
394
 
395
+ export function checkUseWordSearch(formatted) {
396
+ // Note: add a space to startWords to catch just actual boolean words
397
+ const booleanStartWords = ['and ', 'or ', 'nor ', 'not '];
398
+ return booleanStartWords.some(word => formatted.toLowerCase().startsWith(word));
399
+ }
401
400
 
402
401
  export function bibStandardIdentifiers(record) {
403
402
 
@@ -0,0 +1,38 @@
1
+ import assert from 'node:assert';
2
+ import {describe} from 'node:test';
3
+ import createDebugLogger from 'debug';
4
+ import generateTests from '@natlibfi/fixugen';
5
+ import {READERS} from '@natlibfi/fixura';
6
+ import {MarcRecord} from '@natlibfi/marc-record';
7
+ import * as generators from './bib.js';
8
+
9
+ const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query:bibHostComponents:test');
10
+ const debugData = debug.extend('data');
11
+
12
+ describe('candidate-search/query-list/bib/', () => {
13
+ generateTests({
14
+ path: [import.meta.dirname, '..', '..', '..', 'test-fixtures', 'candidate-search', 'query-list', 'bib'],
15
+ useMetadataFile: true,
16
+ fixura: {
17
+ reader: READERS.JSON
18
+ },
19
+ callback: ({type, inputRecord, expectedQuery, expectedQueryListType, enabled = true}) => {
20
+ const generate = generators[type];
21
+ const record = new MarcRecord(inputRecord, {subfieldValues: false});
22
+
23
+ if (!enabled) {
24
+ return;
25
+ }
26
+
27
+ const result = generate(record);
28
+ debugData(`Result: ${JSON.stringify(result)}`);
29
+
30
+ if (result.queryListType) {
31
+ assert.deepStrictEqual(result.queryList, expectedQuery);
32
+ assert.equal(result.queryListType, expectedQueryListType);
33
+ return;
34
+ }
35
+ assert.deepStrictEqual(result, expectedQuery);
36
+ }
37
+ });
38
+ });
@@ -0,0 +1,127 @@
1
+ import createDebugLogger from 'debug';
2
+ import {promisify} from 'util';
3
+ import {toQueries} from '../candidate-search-utils.js';
4
+ import {getSubfieldValues, testStringOrNumber, toMelindaIds} from '../../matching-utils.js';
5
+
6
+ const setTimeoutPromise = promisify(setTimeout); // eslint-disable-line
7
+
8
+ export function hostIdMelinda(record) {
9
+ const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query:hostIdMelinda');
10
+ const debugData = debug.extend('data'); // eslint-disable-line
11
+ debug(`Creating query for the Melinda Id host`);
12
+
13
+ const ids = hostId(record);
14
+ if (ids.length > 0) {
15
+ return toQueries(ids, 'melinda.partsofhost');
16
+ }
17
+
18
+ debug(`No valid Melinda Id host found`);
19
+ return [];
20
+
21
+ function hostId(record) {
22
+ // Multi 773 handling
23
+ const f773s = record.get(/^773$/u)
24
+ .filter(f773 => f773.subfields.some(sub => sub.code === 'w' && (/\(FI-MELINDA\).*/ui).test(sub.value)));
25
+
26
+ if (f773s.length === 0) {
27
+ return false;
28
+ }
29
+
30
+ // Multi $w handling
31
+ // $w (prefix)<id> handling
32
+ // $w <id> & $w (prefix)<id> Match
33
+ const melindaIds = f773s.map(f773 => toMelindaIds(f773, ['w'])).flat()
34
+ .filter(value => testStringOrNumber(value)) // drop invalid values
35
+ .filter((value, index, array) => array.indexOf(value) === index); // unique values;
36
+ return melindaIds;
37
+ }
38
+ }
39
+
40
+ export async function hostIdOtherSource(record, client) {
41
+ const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query:hostIdOtherSource');
42
+ const debugData = debug.extend('data'); // eslint-disable-line
43
+ debug(`Creating query for the Other source Id host`);
44
+
45
+ const ids = getHostIds(record);
46
+ const otherSources = getOtherSources(record);
47
+ if (ids.length > 0 && otherSources.length > 0) {
48
+ const otherSourceIds = ids.map(id => otherSources.map(source => `${id}${source}`)).flat();
49
+ const melindaHostQueries = await handleSruCalls(otherSourceIds);
50
+ debug(JSON.stringify(melindaHostQueries));
51
+
52
+ return melindaHostQueries;
53
+ }
54
+
55
+ debug(`No valid other source hosts found`);
56
+ return [];
57
+
58
+
59
+ function getHostIds(record) {
60
+ const f773s = record.get(/^773$/u)
61
+ .filter(f773 => f773.subfields.some(sub => sub.code === 'w' && !(/\(FI-MELINDA\).*/ui).test(sub.value)));
62
+ if (f773s.length === 0) {
63
+ return false;
64
+ }
65
+
66
+ // Multi 773 handling
67
+ const subfieldWs = f773s
68
+ .map(f773 => {
69
+ debugData(`f773: ${JSON.stringify(f773)}`);
70
+ return getSubfieldValues(f773, 'w').flat();
71
+ }).flat();
72
+
73
+ // Multi $w handling
74
+ // $w (prefix)<id> handling
75
+ // $w <id> & $w (prefix)<id> Match
76
+ const ids = subfieldWs.map(value => `${value}`.replace(/\(FI-.*\)/ui, '')) // remove prefixes
77
+ .filter(value => testStringOrNumber(value)) // drop invalid values
78
+ .filter((value, index, array) => array.indexOf(value) === index); // unique values
79
+
80
+ return ids;
81
+ }
82
+
83
+ function getOtherSources(record) {
84
+ const fSids = record.get('SID');
85
+ return fSids.map(field => getSubfieldValues(field, 'b'));
86
+ }
87
+
88
+ async function handleSruCalls(otherSourceIds, ids = []) {
89
+ const [otherSourceId, ...rest] = otherSourceIds;
90
+
91
+ if (otherSourceId === undefined) {
92
+ debug(`host ids: ${ids}`);
93
+ const validIds = ids.filter(id => id);
94
+ return toQueries(validIds, 'melinda.partsofhost');
95
+ }
96
+
97
+ const otherSourceHostQuery = await toQueries([otherSourceId], 'melinda.sourceid');
98
+ const id = await new Promise((resolve, reject) => {
99
+ debug(`Searching for hosts with query: ${otherSourceHostQuery}`);
100
+ let recordId;
101
+
102
+ client.searchRetrieve(otherSourceHostQuery)
103
+ .on('error', err => {
104
+ debug(`SRU error for query: ${otherSourceHostQuery}: ${err}`);
105
+ reject(err);
106
+ })
107
+ .on('end', async () => {
108
+ try {
109
+ debug(`Searching for hosts: done`);
110
+ await setTimeoutPromise(10);
111
+ resolve(recordId);
112
+ } catch (err) {
113
+ debug(`Error caught on END`);
114
+ reject(err);
115
+ }
116
+ })
117
+ .on('record', record => {
118
+ const [field] = record.get(/^001$/u);
119
+ debug(field);
120
+ recordId = field.value ? field.value : '';
121
+ });
122
+ });
123
+
124
+ return handleSruCalls(rest, [...ids, id]);
125
+ }
126
+ }
127
+
@@ -1,32 +1,9 @@
1
- /**
2
- *
3
- * @licstart The following is the entire license notice for the JavaScript code in this file.
4
- *
5
- * Melinda record matching modules for Javascript
6
- *
7
- * Copyright (C) 2020-2022 University Of Helsinki (The National Library Of Finland)
8
- *
9
- * This file is part of melinda-record-matching-js
10
- *
11
- * melinda-record-matching-js program is free software: you can redistribute it and/or modify
12
- * it under the terms of the GNU Lesser General Public License as
13
- * published by the Free Software Foundation, either version 3 of the
14
- * License, or (at your option) any later version.
15
- *
16
- * melinda-record-matching-js is distributed in the hope that it will be useful,
17
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19
- * GNU Lesser General Public License for more details.
20
- *
21
- * You should have received a copy of the GNU Affero General Public License
22
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
23
- *
24
- * @licend The above is the entire license notice
25
- * for the JavaScript code in this file.
26
- *
27
- */
28
-
29
- import * as bib from './bib';
1
+ import * as bib from './bib.js';
2
+ import * as component from './component.js';
3
+ import createDebugLogger from 'debug';
4
+
5
+ const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:index');
6
+ const debugData = debug.extend('data');
30
7
 
31
8
  export const searchTypes = {
32
9
  bib: {
@@ -35,22 +12,41 @@ export const searchTypes = {
35
12
  title: 'bibTitle', // title ( + first author + first publisher if needed)
36
13
  titleAuthor: 'bibTitleAuthor', // title + first author (or first publisher if no author)
37
14
  titleAuthorYear: 'bibTitleAuthorYear', // title + first author (or first publisher if no author), publishing year
15
+ titleAuthorYearAlternates: 'bibTitleAuthorYearAlternates', // title + first author (or first publisher if no author), publishing year
38
16
  melindaId: 'bibMelindaIds',
39
17
  sourceIds: 'bibSourceIds'
40
18
  //DEVELOP: bibContent: 'bibContent'
19
+ },
20
+ component: {
21
+ hostIdMelinda: 'hostIdMelinda', // 773 $w (FI-MELINDA)
22
+ hostIdOtherSource: 'hostIdOtherSource', // 773 $w !(FI-MELINDA)
23
+ hostIsbn: 'hostIsbn' // 773 $z
41
24
  }
42
25
  };
43
26
 
44
- export default (record, searchSpec) => {
45
- const extractors = {...bib};
27
+ export default async (record, searchSpec, client) => {
28
+ const extractors = {...bib, ...component};
29
+ debugData(`extractors: ${JSON.stringify(extractors)}`);
30
+ debugData(`searchSpec: ${JSON.stringify(searchSpec)}`);
31
+
32
+ const qExtractors = searchSpec.map(generateQueryExtractor);
33
+ const results = await handleQextractors(qExtractors);
34
+ return results;
35
+
36
+ async function handleQextractors(qExtractors, results = []) {
37
+ const [qExtractor, ...rest] = qExtractors;
46
38
 
47
- return searchSpec
48
- .map(generateQueryExtractor)
49
- .map(cb => cb(record))
50
- .flat();
39
+ if (qExtractor === undefined) {
40
+ return results.flat();
41
+ }
42
+
43
+ const result = await qExtractor(record, client);
44
+ return handleQextractors(rest, [...results, result]);
45
+ }
51
46
 
52
47
  function generateQueryExtractor(type) {
53
48
  if (extractors[type]) {
49
+ //debugData(`${JSON.stringify(extractors[type])}`);
54
50
  return extractors[type];
55
51
  }
56
52