@natlibfi/melinda-record-matching 4.3.2-alpha.2 → 4.3.2-alpha.4
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.
- package/dist/candidate-search/choose-queries.js +150 -0
- package/dist/candidate-search/choose-queries.js.map +1 -0
- package/dist/candidate-search/index.js +36 -52
- package/dist/candidate-search/index.js.map +1 -1
- package/dist/candidate-search/index.spec.js +25 -8
- package/dist/candidate-search/index.spec.js.map +1 -1
- package/dist/candidate-search/query-list/bib.js +9 -8
- package/dist/candidate-search/query-list/bib.js.map +1 -1
- package/dist/index.js +7 -4
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/candidate-search/choose-queries.js +123 -0
- package/src/candidate-search/index.js +20 -53
- package/src/candidate-search/index.spec.js +17 -3
- package/src/candidate-search/query-list/bib.js +3 -2
- package/src/index.js +5 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bib.js","names":["_debug","_interopRequireDefault","require","_candidateSearchUtils","_matchingUtils","obj","__esModule","default","debug","createDebugLogger","bibSourceIds","record","debugData","extend","fSids","get","length","JSON","stringify","toSidQueries","sidStrings","getSidStrings","sidQueries","toQueries","map","toSidString","filter","nonEmptySid","field","validateSidFieldSubfieldCounts","createSidString","sfC","getSubfieldValues","sfB","cleanedSfC","removeSourcePrefix","normalizeSidSubfieldValue","cleanedSfB","concat","subfieldValue","sourcePrefixRegex","normalizedValue","testStringOrNumber","String","replace","normalizeAwayRegex","bibMelindaIds","melindaIds","getMelindaIdsF035","bibHostComponents","id","getHostId","value","subfields","find","code","test","bibTitle","bibTitleAuthorPublisher","onlyTitleLength","bibTitleAuthor","bibTitleAuthorYear","addYear","bibTitleAuthorYearAlternates","queryList","alternates","alternateQueries","queryListType","title","getTitle","booleanStartWords","formatted","trim","slice","useWordSearch","some","word","toLowerCase","startsWith","queryIsOkAlone","query","newAlternateQueries","addAuthorsToSearch","authorQuery","bibAuthors","undefined","addYearToSearch","addPublisherToSearch","publisherQuery","bibPublishers","yearQuery","bibYear","titleString","includes","join","author","getAuthor","authorString","publisher","getPublisher","publisherString","year","getYear","bibStandardIdentifiers","fields","identifiers","toIdentifiers","uniqueIdentifiers","Set","tag","issnIsbnReqExp","otherIdReqExp","sub"],"sources":["../../../src/candidate-search/query-list/bib.js"],"sourcesContent":["\n/**\n*\n* @licstart The following is the entire license notice for the JavaScript code in this file.\n*\n* Melinda record matching modules for Javascript\n*\n* Copyright (C) 2020-2023 University Of Helsinki (The National Library Of Finland)\n*\n* This file is part of melinda-record-matching-js\n*\n* melinda-record-matching-js program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Lesser General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* melinda-record-matching-js is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n*\n* @licend The above is the entire license notice\n* for the JavaScript code in this file.\n*\n*/\nimport createDebugLogger from 'debug';\nimport {toQueries} from '../candidate-search-utils';\nimport {getMelindaIdsF035, validateSidFieldSubfieldCounts, getSubfieldValues, testStringOrNumber} from '../../matching-utils';\n\nconst debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query');\n\nexport function bibSourceIds(record) {\n\n /* Melinda's SRU-index melinda.sourceid includes source IDs from SID fields in Melinda records\n SID-fields in Melinda have sf $c with local id and sf $b with a code for the local db:\n\n SID__ $c 123457 $b helka\n SID__ $c (ANDL100020)1077305 $b sata\n SID__ $c VER999999 $ FI-KV\n SID__ $c /10024/508126 $ REPO_THESEUS\n\n In melinda.sourceid -index case is kept, sourceprefixes in brackets and hyphens are normalized away:\n Note: slashes are not normalized away, but a SRU-search-string including slashes needs to be quoted\n\n 1234567helka\n 1077305sata\n VER999999FIKV\n /10024/508126REPO_THESEUS\n\n Note: All Melinda records that have a matching records in a local db do NOT have SID for that local records,\n existence of a SID field depends on how the record has been added to Melinda and how it has been handled\n afterwards. SIDs are also not reliably maintained. A record might or might not have a SID for a local db\n after the matching record is removed from the local db.\n\n */\n\n\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query:source-ids');\n const debugData = debug.extend('data');\n //const debugInfo = debug.extend('info');\n\n debug(`Creating queries for sourceid's`);\n\n const fSids = record.get('SID');\n debugData(`SID-fields (${fSids.length}): ${JSON.stringify(fSids)}`);\n\n return fSids.length > 0 ? toSidQueries(fSids) : [];\n\n function toSidQueries(fSids) {\n debug(`Creating actual queries for sourceid's`);\n\n const sidStrings = getSidStrings(fSids);\n\n if (sidStrings.length < 1) {\n debug(`No identifiers found, no queries created.`);\n return [];\n }\n\n const sidQueries = toQueries(sidStrings, 'melinda.sourceid');\n\n return sidQueries;\n\n function getSidStrings(fSids) {\n debug(`Getting Sid strings from SID fields`);\n\n // Map SID fields to valid sidStrings, filter out empty strings\n const sidStrings = fSids.map(toSidString).filter(nonEmptySid => nonEmptySid);\n return sidStrings;\n\n function toSidString(field) {\n debug(`Getting string from a field`);\n\n return validateSidFieldSubfieldCounts(field) ? createSidString(field) : '';\n\n function createSidString(field) {\n debug(`Creating string from a field`);\n const [sfC] = getSubfieldValues(field, 'c');\n const [sfB] = getSubfieldValues(field, 'b');\n\n const cleanedSfC = removeSourcePrefix(normalizeSidSubfieldValue(sfC));\n const cleanedSfB = normalizeSidSubfieldValue(sfB);\n\n debugData(`${JSON.stringify(sfC)} + ${JSON.stringify(sfB)}`);\n return cleanedSfC.concat(cleanedSfB);\n }\n\n function removeSourcePrefix(subfieldValue) {\n const sourcePrefixRegex = (/^(?<sourcePrefix>\\([A-Za-z0-9-]+\\))(?<id>.+)$/u);\n const normalizedValue = testStringOrNumber(subfieldValue) ? String(subfieldValue).replace(sourcePrefixRegex, '$<id>') : '';\n debugData(`Normalized ${subfieldValue} to ${normalizedValue}`);\n return normalizedValue;\n }\n\n function normalizeSidSubfieldValue(subfieldValue) {\n debugData(`Normalizing ${subfieldValue}`);\n const normalizeAwayRegex = (/[- ]/u);\n return testStringOrNumber(subfieldValue) ? String(subfieldValue).replace(normalizeAwayRegex, '') : '';\n }\n\n }\n }\n }\n}\n\nexport function bibMelindaIds(record) {\n // Melinda's SRU-index melinda.melindaid includes f001 controlnumbers and old Melinda-IDs from f035z's for all non-deleted Melinda-records\n\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query:bibMelindaIds');\n const debugData = debug.extend('data');\n debug(`Creating queries for MelindaIds`);\n\n // Note: Melinda-ID's for search queries are created just from records f035a's and f035z's\n // Both (FI-MELINDA)- and FCC-prefixed forms are found\n // f001 controlnumber is not currently included, even if record's f003 is FI-MELINDA\n const melindaIds = getMelindaIdsF035(record);\n\n debugData(`Unique identifiers (${melindaIds.length}): ${JSON.stringify(melindaIds)}`);\n\n if (melindaIds.length < 1) {\n debug(`No identifiers found, no queries created.`);\n return [];\n }\n\n return toQueries(melindaIds, 'melinda.melindaid');\n}\n\n\n// bibHostComponents returns host id from the first subfield $w of first field f773, see test-fixtures 04 and 05\n// bibHostComponents should search all 773 $ws for possible host id, but what should it do in case of multiple host ids?\nexport function bibHostComponents(record) {\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query:bibHostComponents');\n const debugData = debug.extend('data');\n debug(`Creating queries for hostIds`);\n\n const id = getHostId();\n debugData(`Found id: ${JSON.stringify(id)}`);\n\n return testStringOrNumber(id) ? [`melinda.partsofhost=${id}`] : [];\n\n function getHostId() {\n const [field] = record.get(/^773$/u);\n\n if (field) {\n const {value} = field.subfields.find(({code}) => code === 'w') || {};\n\n if (testStringOrNumber(value) && (/^\\(FI-MELINDA\\)/u).test(String(value))) {\n return String(value).replace(/^\\(FI-MELINDA\\)/u, '');\n }\n\n if (testStringOrNumber(value) && (/^\\(FIN01\\)/u).test(String(value))) {\n return String(value).replace(/^\\(FIN01\\)/u, '');\n }\n\n return false;\n }\n return false;\n }\n}\n\n// SRU search dc.title with a search phrase starting with ^ maps currently in Melinda to\n// (probably) to *headings* index TIT\n// - Aleph cannot currently handle headings searches starting with a boolean - in these cases use word search\n\n// Headings index TIT drops articles etc. from the start of the title according to the filing indicator\n// Currently filing indicator is not implemented - if the title starts with an article and the Melinda\n// record is correctly catalogued using a filing indicator -> dc.title search won't match\n\nexport function bibTitle(record) {\n // We get author/publisher only when formatted title is shorter than 5 chars\n return bibTitleAuthorPublisher({record, onlyTitleLength: 5});\n}\n\nexport function bibTitleAuthor(record) {\n debug('bibTitleAuthor');\n // We use onlyTitleLength that is longer than our formatted length to\n // get an author or an publisher always\n return bibTitleAuthorPublisher({record, onlyTitleLength: 100});\n}\n\nexport function bibTitleAuthorYear(record) {\n debug('bibTitleAuthorYearAlternates');\n // We use onlyTitleLength that is longer than our formatted length to\n // get an author or an publisher always\n\n return bibTitleAuthorPublisher({record, onlyTitleLength: 100, addYear: true});\n}\n\nexport function bibTitleAuthorYearAlternates(record) {\n debug('bibTitleAuthorYearAlternates');\n // We use onlyTitleLength that is longer than our formatted length to\n // get an author or an publisher always\n\n return {queryList: bibTitleAuthorPublisher({record, onlyTitleLength: 100, addYear: true, alternates: true, alternateQueries: []}), queryListType: 'alternates'};\n}\n\nexport function bibTitleAuthorPublisher({record, onlyTitleLength, addYear = false, alternates = false, alternateQueries = []}) {\n debug(`bibTitleAuthorPublisher, onlyTitleLength: ${onlyTitleLength}, addYear: ${addYear}, alternates: ${alternates}`);\n const title = getTitle();\n const booleanStartWords = ['and', 'or', 'nor', 'not'];\n\n if (testStringOrNumber(title)) {\n const formatted = String(title)\n .replace(/[^\\w\\s\\p{Alphabetic}]/gu, '')\n // Clean up concurrent spaces from fe. subfield changes\n .replace(/ +/gu, ' ')\n .trim()\n .slice(0, 30)\n .trim();\n\n // use word search for titles starting with a boolean\n const useWordSearch = booleanStartWords.some(word => formatted.toLowerCase().startsWith(word));\n // Prevent too many matches / SRU crashing by having a minimum length\n // Note that currently this fails matching if there are no matches from previous matchers\n if (formatted.length >= onlyTitleLength && !alternates) {\n return [`dc.title=\"${useWordSearch ? '' : '^'}${formatted}*\"`];\n }\n const queryIsOkAlone = formatted.length >= 5;\n\n // use word search without ending * also in combination searches to avoid SRU-server crashes [MRA-189]\n const query = `dc.title=\"${useWordSearch || !queryIsOkAlone ? '' : '^'}${formatted}${queryIsOkAlone ? '*' : ''}\"`;\n debug(`query: ${query}`);\n const newAlternateQueries = alternates ? [...alternateQueries, query] : alternateQueries;\n\n return addAuthorsToSearch({query, queryIsOkAlone, addYear, alternates, alternateQueries: newAlternateQueries});\n }\n\n return [];\n\n function addAuthorsToSearch({query, queryIsOkAlone = false, addYear = false, alternates = false, alternateQueries = []}) {\n debug('addAuthorsToSearch');\n const [authorQuery] = bibAuthors(record);\n if (authorQuery !== undefined) {\n if (addYear) {\n const newAlternateQueries = alternates ? [...alternateQueries, `${authorQuery} AND ${query}`] : alternateQueries;\n return addYearToSearch({query: `${authorQuery} AND ${query}`, queryIsOkAlone: true, alternates, alternateQueries: newAlternateQueries});\n }\n return alternates ? alternateQueries : [`${authorQuery} AND ${query}`];\n }\n return addPublisherToSearch({query, queryIsOkAlone, addYear, alternates, alternateQueries});\n //return [];\n }\n\n function addPublisherToSearch({query, queryIsOkAlone = false, addYear = false, alternates = false, alternateQueries = []}) {\n const [publisherQuery] = bibPublishers(record);\n if (publisherQuery !== undefined) {\n if (addYear) {\n const newAlternateQueries = alternates ? [...alternateQueries, `${publisherQuery} AND ${query}`] : alternateQueries;\n return addYearToSearch({query: `${publisherQuery} AND ${query}`, queryIsOkAlone: true, alternates, alternateQueries: newAlternateQueries});\n }\n return alternates ? alternateQueries : [`${publisherQuery} AND ${query}`];\n }\n if (queryIsOkAlone && !addYear) {\n return alternates ? alternateQueries : [`${query}`];\n }\n return addYearToSearch({query, queryIsOkAlone, alternates, alternateQueries});\n }\n\n function addYearToSearch({query, queryIsOkAlone = false, alternates = false, alternateQueries = []}) {\n const [yearQuery] = bibYear(record);\n if (yearQuery !== undefined) {\n const newAlternateQueries = alternates ? [...alternateQueries, `${yearQuery} AND ${query}`] : alternateQueries;\n return alternates ? newAlternateQueries : [`${yearQuery} AND ${query}`];\n }\n if (queryIsOkAlone) {\n return alternates ? alternateQueries : [`${query}`];\n }\n return [];\n }\n\n function getTitle() {\n const [field] = record.get(/^245$/u);\n\n if (field) {\n const titleString = field.subfields\n //.filter(({code}) => ['a', 'b', 'n', 'p'].includes(code))\n .filter(({code}) => ['a', 'b'].includes(code))\n //.filter(({code}) => ['a'].includes(code))\n .map(({value}) => testStringOrNumber(value) ? String(value) : '')\n .filter(value => value)\n // In Melinda's index subfield separators are indexed as ' '\n .join(' ');\n return titleString;\n }\n return false;\n }\n}\n\nexport function bibAuthors(record) {\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query:bibAuthors');\n const debugData = debug.extend('data');\n debug(`Creating query for the first author`);\n //debugData(record);\n\n const author = getAuthor(record);\n const booleanStartWords = ['and', 'or', 'nor', 'not'];\n\n\n if (testStringOrNumber(author)) {\n const formatted = String(author)\n .replace(/[^\\w\\s\\p{Alphabetic}]/gu, '')\n // Clean up concurrent spaces from fe. subfield changes\n .replace(/ +/gu, ' ')\n .trim()\n .slice(0, 30)\n .trim();\n\n // use word search for authors starting with a boolean\n const useWordSearch = booleanStartWords.some(word => formatted.toLowerCase().startsWith(word));\n // Prevent too many matches by having a minimum length\n debugData(`Author string: ${formatted}`);\n if (formatted.length >= 5) {\n return [`dc.author=\"${useWordSearch ? '' : '^'}${formatted}*\"`];\n }\n return [];\n }\n\n return [];\n\n function getAuthor(record) {\n //debugData(record);\n // eslint-disable-next-line prefer-named-capture-group\n const [field] = record.get(/^(100)|(110)|(111)|(700)|(710)|(711)$/u);\n //debugData(field);\n\n if (field) {\n const authorString = field.subfields\n .filter(({code}) => ['a'].includes(code))\n .map(({value}) => testStringOrNumber(value) ? String(value) : '')\n .filter(value => value)\n // In Melinda's index subfield separators are indexed as ' '\n .join(' ');\n return authorString;\n }\n return false;\n }\n}\n\nexport function bibPublishers(record) {\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query:bibPublishers');\n const debugData = debug.extend('data');\n debug(`Creating query for the first publisher`);\n //debugData(record);\n\n const publisher = getPublisher(record);\n if (testStringOrNumber(publisher)) {\n const formatted = String(publisher)\n .replace(/[^\\w\\s\\p{Alphabetic}]/gu, '')\n // Clean up concurrent spaces from fe. subfield changes\n .replace(/ +/gu, ' ')\n .trim()\n .slice(0, 30)\n .trim();\n\n debugData(`Publisher string: ${formatted}`);\n // use non-wildcard word search from dc.publisher\n return [`dc.publisher=\"${formatted}\"`];\n }\n\n return [];\n\n function getPublisher(record) {\n //debugData(record);\n const [field] = record.get(/^(?:260)|(?:264)$/u);\n //debugData(field);\n\n if (field) {\n const publisherString = field.subfields\n .filter(({code}) => ['b'].includes(code))\n .map(({value}) => testStringOrNumber(value) ? String(value) : '')\n .filter(value => value)\n // In Melinda's index subfield separators are indexed as ' '\n .join(' ');\n return publisherString;\n }\n return false;\n }\n}\n\nexport function bibYear(record) {\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query:bibYear');\n const debugData = debug.extend('data');\n debug(`Creating query for the publishing year`);\n debugData(record);\n\n const year = getYear(record);\n if (year) {\n return [`dc.date=\"${year}\"`];\n }\n return [];\n\n function getYear(record) {\n const value = record.get(/^008$/u)?.[0]?.value || undefined;\n return testStringOrNumber(value) ? String(value).slice(7, 11) : undefined;\n }\n}\n\n\nexport function bibStandardIdentifiers(record) {\n\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query:bibStandardIdentifiers');\n const debugData = debug.extend('data');\n debug(`Creating queries for standard identifiers`);\n\n // DEVELOP: should we query also f015 and f028?\n\n const fields = record.get(/^(?<def>020|022|024)$/u);\n const identifiers = [].concat(...fields.map(toIdentifiers));\n const uniqueIdentifiers = [...new Set(identifiers)];\n\n debugData(`Standard identifier fields: ${JSON.stringify(fields)}`);\n debugData(`Identifiers (${identifiers.length}): ${JSON.stringify(identifiers)}`);\n debugData(`Unique identifiers (${uniqueIdentifiers.length}): ${JSON.stringify(uniqueIdentifiers)}`);\n\n if (uniqueIdentifiers.length < 1) {\n debug(`No identifiers found, no queries created.`);\n return [];\n }\n\n return toQueries(uniqueIdentifiers, 'dc.identifier');\n\n function toIdentifiers({tag, subfields}) {\n const issnIsbnReqExp = (/^[A-Za-z0-9-]+$/u);\n const otherIdReqExp = (/^[A-Za-z0-9-:]+$/u);\n\n if (tag === '022') {\n return subfields\n .filter(sub => ['a', 'z', 'y'].includes(sub.code) && testStringOrNumber(sub.value) && issnIsbnReqExp.test(String(sub.value)))\n .map(({value}) => String(value));\n }\n\n if (tag === '020') {\n return subfields\n .filter(sub => ['a', 'z'].includes(sub.code) && testStringOrNumber(sub.value) && issnIsbnReqExp.test(String(sub.value)))\n .map(({value}) => String(value));\n }\n\n return subfields\n .filter(sub => ['a', 'z'].includes(sub.code) && testStringOrNumber(sub.value) && otherIdReqExp.test(String(sub.value)))\n .map(({value}) => String(value));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA4BA,IAAAA,MAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,qBAAA,GAAAD,OAAA;AACA,IAAAE,cAAA,GAAAF,OAAA;AAA8H,SAAAD,uBAAAI,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,KAAAE,OAAA,EAAAF,GAAA;AA7B9H;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAKA,MAAMG,KAAK,GAAG,IAAAC,cAAiB,EAAC,0DAA0D,CAAC;AAEpF,SAASC,YAAYA,CAACC,MAAM,EAAE;EAEnC;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;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5D,KAAK,CAAC,IAAI2D,aAAa,CAACvD,IAAI,CAACb,MAAM,CAACqE,GAAG,CAAC5D,KAAK,CAAC,CAAC,CAAC,CACtH5B,GAAG,CAAC,CAAC;MAAC4B;IAAK,CAAC,KAAKT,MAAM,CAACS,KAAK,CAAC,CAAC;EACpC;AACF"}
|
|
1
|
+
{"version":3,"file":"bib.js","names":["_debug","_interopRequireDefault","require","_candidateSearchUtils","_matchingUtils","obj","__esModule","default","debug","createDebugLogger","bibSourceIds","record","debugData","extend","fSids","get","length","JSON","stringify","toSidQueries","sidStrings","getSidStrings","sidQueries","toQueries","map","toSidString","filter","nonEmptySid","field","validateSidFieldSubfieldCounts","createSidString","sfC","getSubfieldValues","sfB","cleanedSfC","removeSourcePrefix","normalizeSidSubfieldValue","cleanedSfB","concat","subfieldValue","sourcePrefixRegex","normalizedValue","testStringOrNumber","String","replace","normalizeAwayRegex","bibMelindaIds","melindaIds","getMelindaIdsF035","bibHostComponents","id","getHostId","value","subfields","find","code","test","bibTitle","bibTitleAuthorPublisher","onlyTitleLength","bibTitleAuthor","bibTitleAuthorYear","addYear","bibTitleAuthorYearAlternates","origQueryList","alternates","alternateQueries","queryList","Array","from","reverse","queryListType","title","getTitle","booleanStartWords","formatted","trim","slice","useWordSearch","some","word","toLowerCase","startsWith","queryIsOkAlone","query","newAlternateQueries","addAuthorsToSearch","authorQuery","bibAuthors","undefined","addYearToSearch","addPublisherToSearch","publisherQuery","bibPublishers","yearQuery","bibYear","titleString","includes","join","author","getAuthor","authorString","publisher","getPublisher","publisherString","year","getYear","bibStandardIdentifiers","fields","identifiers","toIdentifiers","uniqueIdentifiers","Set","tag","issnIsbnReqExp","otherIdReqExp","sub"],"sources":["../../../src/candidate-search/query-list/bib.js"],"sourcesContent":["\n/**\n*\n* @licstart The following is the entire license notice for the JavaScript code in this file.\n*\n* Melinda record matching modules for Javascript\n*\n* Copyright (C) 2020-2023 University Of Helsinki (The National Library Of Finland)\n*\n* This file is part of melinda-record-matching-js\n*\n* melinda-record-matching-js program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Lesser General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* melinda-record-matching-js is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n*\n* @licend The above is the entire license notice\n* for the JavaScript code in this file.\n*\n*/\nimport createDebugLogger from 'debug';\nimport {toQueries} from '../candidate-search-utils';\nimport {getMelindaIdsF035, validateSidFieldSubfieldCounts, getSubfieldValues, testStringOrNumber} from '../../matching-utils';\n\nconst debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query');\n\nexport function bibSourceIds(record) {\n\n /* Melinda's SRU-index melinda.sourceid includes source IDs from SID fields in Melinda records\n SID-fields in Melinda have sf $c with local id and sf $b with a code for the local db:\n\n SID__ $c 123457 $b helka\n SID__ $c (ANDL100020)1077305 $b sata\n SID__ $c VER999999 $ FI-KV\n SID__ $c /10024/508126 $ REPO_THESEUS\n\n In melinda.sourceid -index case is kept, sourceprefixes in brackets and hyphens are normalized away:\n Note: slashes are not normalized away, but a SRU-search-string including slashes needs to be quoted\n\n 1234567helka\n 1077305sata\n VER999999FIKV\n /10024/508126REPO_THESEUS\n\n Note: All Melinda records that have a matching records in a local db do NOT have SID for that local records,\n existence of a SID field depends on how the record has been added to Melinda and how it has been handled\n afterwards. SIDs are also not reliably maintained. A record might or might not have a SID for a local db\n after the matching record is removed from the local db.\n\n */\n\n\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query:source-ids');\n const debugData = debug.extend('data');\n //const debugInfo = debug.extend('info');\n\n debug(`Creating queries for sourceid's`);\n\n const fSids = record.get('SID');\n debugData(`SID-fields (${fSids.length}): ${JSON.stringify(fSids)}`);\n\n return fSids.length > 0 ? toSidQueries(fSids) : [];\n\n function toSidQueries(fSids) {\n debug(`Creating actual queries for sourceid's`);\n\n const sidStrings = getSidStrings(fSids);\n\n if (sidStrings.length < 1) {\n debug(`No identifiers found, no queries created.`);\n return [];\n }\n\n const sidQueries = toQueries(sidStrings, 'melinda.sourceid');\n\n return sidQueries;\n\n function getSidStrings(fSids) {\n debug(`Getting Sid strings from SID fields`);\n\n // Map SID fields to valid sidStrings, filter out empty strings\n const sidStrings = fSids.map(toSidString).filter(nonEmptySid => nonEmptySid);\n return sidStrings;\n\n function toSidString(field) {\n debug(`Getting string from a field`);\n\n return validateSidFieldSubfieldCounts(field) ? createSidString(field) : '';\n\n function createSidString(field) {\n debug(`Creating string from a field`);\n const [sfC] = getSubfieldValues(field, 'c');\n const [sfB] = getSubfieldValues(field, 'b');\n\n const cleanedSfC = removeSourcePrefix(normalizeSidSubfieldValue(sfC));\n const cleanedSfB = normalizeSidSubfieldValue(sfB);\n\n debugData(`${JSON.stringify(sfC)} + ${JSON.stringify(sfB)}`);\n return cleanedSfC.concat(cleanedSfB);\n }\n\n function removeSourcePrefix(subfieldValue) {\n const sourcePrefixRegex = (/^(?<sourcePrefix>\\([A-Za-z0-9-]+\\))(?<id>.+)$/u);\n const normalizedValue = testStringOrNumber(subfieldValue) ? String(subfieldValue).replace(sourcePrefixRegex, '$<id>') : '';\n debugData(`Normalized ${subfieldValue} to ${normalizedValue}`);\n return normalizedValue;\n }\n\n function normalizeSidSubfieldValue(subfieldValue) {\n debugData(`Normalizing ${subfieldValue}`);\n const normalizeAwayRegex = (/[- ]/u);\n return testStringOrNumber(subfieldValue) ? String(subfieldValue).replace(normalizeAwayRegex, '') : '';\n }\n\n }\n }\n }\n}\n\nexport function bibMelindaIds(record) {\n // Melinda's SRU-index melinda.melindaid includes f001 controlnumbers and old Melinda-IDs from f035z's for all non-deleted Melinda-records\n\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query:bibMelindaIds');\n const debugData = debug.extend('data');\n debug(`Creating queries for MelindaIds`);\n\n // Note: Melinda-ID's for search queries are created just from records f035a's and f035z's\n // Both (FI-MELINDA)- and FCC-prefixed forms are found\n // f001 controlnumber is not currently included, even if record's f003 is FI-MELINDA\n const melindaIds = getMelindaIdsF035(record);\n\n debugData(`Unique identifiers (${melindaIds.length}): ${JSON.stringify(melindaIds)}`);\n\n if (melindaIds.length < 1) {\n debug(`No identifiers found, no queries created.`);\n return [];\n }\n\n return toQueries(melindaIds, 'melinda.melindaid');\n}\n\n\n// bibHostComponents returns host id from the first subfield $w of first field f773, see test-fixtures 04 and 05\n// bibHostComponents should search all 773 $ws for possible host id, but what should it do in case of multiple host ids?\nexport function bibHostComponents(record) {\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query:bibHostComponents');\n const debugData = debug.extend('data');\n debug(`Creating queries for hostIds`);\n\n const id = getHostId();\n debugData(`Found id: ${JSON.stringify(id)}`);\n\n return testStringOrNumber(id) ? [`melinda.partsofhost=${id}`] : [];\n\n function getHostId() {\n const [field] = record.get(/^773$/u);\n\n if (field) {\n const {value} = field.subfields.find(({code}) => code === 'w') || {};\n\n if (testStringOrNumber(value) && (/^\\(FI-MELINDA\\)/u).test(String(value))) {\n return String(value).replace(/^\\(FI-MELINDA\\)/u, '');\n }\n\n if (testStringOrNumber(value) && (/^\\(FIN01\\)/u).test(String(value))) {\n return String(value).replace(/^\\(FIN01\\)/u, '');\n }\n\n return false;\n }\n return false;\n }\n}\n\n// SRU search dc.title with a search phrase starting with ^ maps currently in Melinda to\n// (probably) to *headings* index TIT\n// - Aleph cannot currently handle headings searches starting with a boolean - in these cases use word search\n\n// Headings index TIT drops articles etc. from the start of the title according to the filing indicator\n// Currently filing indicator is not implemented - if the title starts with an article and the Melinda\n// record is correctly catalogued using a filing indicator -> dc.title search won't match\n\nexport function bibTitle(record) {\n // We get author/publisher only when formatted title is shorter than 5 chars\n return bibTitleAuthorPublisher({record, onlyTitleLength: 5});\n}\n\nexport function bibTitleAuthor(record) {\n debug('bibTitleAuthor');\n // We use onlyTitleLength that is longer than our formatted length to\n // get an author or an publisher always\n return bibTitleAuthorPublisher({record, onlyTitleLength: 100});\n}\n\nexport function bibTitleAuthorYear(record) {\n debug('bibTitleAuthorYearAlternates');\n // We use onlyTitleLength that is longer than our formatted length to\n // get an author or an publisher always\n\n return bibTitleAuthorPublisher({record, onlyTitleLength: 100, addYear: true});\n}\n\nexport function bibTitleAuthorYearAlternates(record) {\n debug('bibTitleAuthorYearAlternates');\n // We use onlyTitleLength that is longer than our formatted length to\n // get an author or an publisher always\n const origQueryList = bibTitleAuthorPublisher({record, onlyTitleLength: 100, addYear: true, alternates: true, alternateQueries: []});\n debug(`${JSON.stringify(origQueryList)}`);\n return {queryList: Array.from(origQueryList).reverse(), queryListType: 'alternates'};\n}\n\nexport function bibTitleAuthorPublisher({record, onlyTitleLength, addYear = false, alternates = false, alternateQueries = []}) {\n debug(`bibTitleAuthorPublisher, onlyTitleLength: ${onlyTitleLength}, addYear: ${addYear}, alternates: ${alternates}`);\n const title = getTitle();\n const booleanStartWords = ['and', 'or', 'nor', 'not'];\n\n if (testStringOrNumber(title)) {\n const formatted = String(title)\n .replace(/[^\\w\\s\\p{Alphabetic}]/gu, '')\n // Clean up concurrent spaces from fe. subfield changes\n .replace(/ +/gu, ' ')\n .trim()\n .slice(0, 30)\n .trim();\n\n // use word search for titles starting with a boolean\n const useWordSearch = booleanStartWords.some(word => formatted.toLowerCase().startsWith(word));\n // Prevent too many matches / SRU crashing by having a minimum length\n // Note that currently this fails matching if there are no matches from previous matchers\n if (formatted.length >= onlyTitleLength && !alternates) {\n return [`dc.title=\"${useWordSearch ? '' : '^'}${formatted}*\"`];\n }\n const queryIsOkAlone = formatted.length >= 5;\n\n // use word search without ending * also in combination searches to avoid SRU-server crashes [MRA-189]\n const query = `dc.title=\"${useWordSearch || !queryIsOkAlone ? '' : '^'}${formatted}${queryIsOkAlone ? '*' : ''}\"`;\n debug(`query: ${query}`);\n const newAlternateQueries = alternates ? [...alternateQueries, query] : alternateQueries;\n\n return addAuthorsToSearch({query, queryIsOkAlone, addYear, alternates, alternateQueries: newAlternateQueries});\n }\n\n return [];\n\n function addAuthorsToSearch({query, queryIsOkAlone = false, addYear = false, alternates = false, alternateQueries = []}) {\n debug('addAuthorsToSearch');\n const [authorQuery] = bibAuthors(record);\n if (authorQuery !== undefined) {\n if (addYear) {\n const newAlternateQueries = alternates ? [...alternateQueries, `${authorQuery} AND ${query}`] : alternateQueries;\n return addYearToSearch({query: `${authorQuery} AND ${query}`, queryIsOkAlone: true, alternates, alternateQueries: newAlternateQueries});\n }\n return alternates ? alternateQueries : [`${authorQuery} AND ${query}`];\n }\n return addPublisherToSearch({query, queryIsOkAlone, addYear, alternates, alternateQueries});\n //return [];\n }\n\n function addPublisherToSearch({query, queryIsOkAlone = false, addYear = false, alternates = false, alternateQueries = []}) {\n const [publisherQuery] = bibPublishers(record);\n if (publisherQuery !== undefined) {\n if (addYear) {\n const newAlternateQueries = alternates ? [...alternateQueries, `${publisherQuery} AND ${query}`] : alternateQueries;\n return addYearToSearch({query: `${publisherQuery} AND ${query}`, queryIsOkAlone: true, alternates, alternateQueries: newAlternateQueries});\n }\n return alternates ? alternateQueries : [`${publisherQuery} AND ${query}`];\n }\n if (queryIsOkAlone && !addYear) {\n return alternates ? alternateQueries : [`${query}`];\n }\n return addYearToSearch({query, queryIsOkAlone, alternates, alternateQueries});\n }\n\n function addYearToSearch({query, queryIsOkAlone = false, alternates = false, alternateQueries = []}) {\n const [yearQuery] = bibYear(record);\n if (yearQuery !== undefined) {\n const newAlternateQueries = alternates ? [...alternateQueries, `${yearQuery} AND ${query}`] : alternateQueries;\n return alternates ? newAlternateQueries : [`${yearQuery} AND ${query}`];\n }\n if (queryIsOkAlone) {\n return alternates ? alternateQueries : [`${query}`];\n }\n return [];\n }\n\n function getTitle() {\n const [field] = record.get(/^245$/u);\n\n if (field) {\n const titleString = field.subfields\n //.filter(({code}) => ['a', 'b', 'n', 'p'].includes(code))\n .filter(({code}) => ['a', 'b'].includes(code))\n //.filter(({code}) => ['a'].includes(code))\n .map(({value}) => testStringOrNumber(value) ? String(value) : '')\n .filter(value => value)\n // In Melinda's index subfield separators are indexed as ' '\n .join(' ');\n return titleString;\n }\n return false;\n }\n}\n\nexport function bibAuthors(record) {\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query:bibAuthors');\n const debugData = debug.extend('data');\n debug(`Creating query for the first author`);\n //debugData(record);\n\n const author = getAuthor(record);\n const booleanStartWords = ['and', 'or', 'nor', 'not'];\n\n\n if (testStringOrNumber(author)) {\n const formatted = String(author)\n .replace(/[^\\w\\s\\p{Alphabetic}]/gu, '')\n // Clean up concurrent spaces from fe. subfield changes\n .replace(/ +/gu, ' ')\n .trim()\n .slice(0, 30)\n .trim();\n\n // use word search for authors starting with a boolean\n const useWordSearch = booleanStartWords.some(word => formatted.toLowerCase().startsWith(word));\n // Prevent too many matches by having a minimum length\n debugData(`Author string: ${formatted}`);\n if (formatted.length >= 5) {\n return [`dc.author=\"${useWordSearch ? '' : '^'}${formatted}*\"`];\n }\n return [];\n }\n\n return [];\n\n function getAuthor(record) {\n //debugData(record);\n // eslint-disable-next-line prefer-named-capture-group\n const [field] = record.get(/^(100)|(110)|(111)|(700)|(710)|(711)$/u);\n //debugData(field);\n\n if (field) {\n const authorString = field.subfields\n .filter(({code}) => ['a'].includes(code))\n .map(({value}) => testStringOrNumber(value) ? String(value) : '')\n .filter(value => value)\n // In Melinda's index subfield separators are indexed as ' '\n .join(' ');\n return authorString;\n }\n return false;\n }\n}\n\nexport function bibPublishers(record) {\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query:bibPublishers');\n const debugData = debug.extend('data');\n debug(`Creating query for the first publisher`);\n //debugData(record);\n\n const publisher = getPublisher(record);\n if (testStringOrNumber(publisher)) {\n const formatted = String(publisher)\n .replace(/[^\\w\\s\\p{Alphabetic}]/gu, '')\n // Clean up concurrent spaces from fe. subfield changes\n .replace(/ +/gu, ' ')\n .trim()\n .slice(0, 30)\n .trim();\n\n debugData(`Publisher string: ${formatted}`);\n // use non-wildcard word search from dc.publisher\n return [`dc.publisher=\"${formatted}\"`];\n }\n\n return [];\n\n function getPublisher(record) {\n //debugData(record);\n const [field] = record.get(/^(?:260)|(?:264)$/u);\n //debugData(field);\n\n if (field) {\n const publisherString = field.subfields\n .filter(({code}) => ['b'].includes(code))\n .map(({value}) => testStringOrNumber(value) ? String(value) : '')\n .filter(value => value)\n // In Melinda's index subfield separators are indexed as ' '\n .join(' ');\n return publisherString;\n }\n return false;\n }\n}\n\nexport function bibYear(record) {\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query:bibYear');\n const debugData = debug.extend('data');\n debug(`Creating query for the publishing year`);\n debugData(record);\n\n const year = getYear(record);\n if (year) {\n return [`dc.date=\"${year}\"`];\n }\n return [];\n\n function getYear(record) {\n const value = record.get(/^008$/u)?.[0]?.value || undefined;\n return testStringOrNumber(value) ? String(value).slice(7, 11) : undefined;\n }\n}\n\n\nexport function bibStandardIdentifiers(record) {\n\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:query:bibStandardIdentifiers');\n const debugData = debug.extend('data');\n debug(`Creating queries for standard identifiers`);\n\n // DEVELOP: should we query also f015 and f028?\n\n const fields = record.get(/^(?<def>020|022|024)$/u);\n const identifiers = [].concat(...fields.map(toIdentifiers));\n const uniqueIdentifiers = [...new Set(identifiers)];\n\n debugData(`Standard identifier fields: ${JSON.stringify(fields)}`);\n debugData(`Identifiers (${identifiers.length}): ${JSON.stringify(identifiers)}`);\n debugData(`Unique identifiers (${uniqueIdentifiers.length}): ${JSON.stringify(uniqueIdentifiers)}`);\n\n if (uniqueIdentifiers.length < 1) {\n debug(`No identifiers found, no queries created.`);\n return [];\n }\n\n return toQueries(uniqueIdentifiers, 'dc.identifier');\n\n function toIdentifiers({tag, subfields}) {\n const issnIsbnReqExp = (/^[A-Za-z0-9-]+$/u);\n const otherIdReqExp = (/^[A-Za-z0-9-:]+$/u);\n\n if (tag === '022') {\n return subfields\n .filter(sub => ['a', 'z', 'y'].includes(sub.code) && testStringOrNumber(sub.value) && issnIsbnReqExp.test(String(sub.value)))\n .map(({value}) => String(value));\n }\n\n if (tag === '020') {\n return subfields\n .filter(sub => ['a', 'z'].includes(sub.code) && testStringOrNumber(sub.value) && issnIsbnReqExp.test(String(sub.value)))\n .map(({value}) => String(value));\n }\n\n return subfields\n .filter(sub => ['a', 'z'].includes(sub.code) && testStringOrNumber(sub.value) && otherIdReqExp.test(String(sub.value)))\n .map(({value}) => String(value));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA4BA,IAAAA,MAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,qBAAA,GAAAD,OAAA;AACA,IAAAE,cAAA,GAAAF,OAAA;AAA8H,SAAAD,uBAAAI,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,KAAAE,OAAA,EAAAF,GAAA;AA7B9H;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAKA,MAAMG,KAAK,GAAG,IAAAC,cAAiB,EAAC,0DAA0D,CAAC;AAEpF,SAASC,YAAYA,CAACC,MAAM,EAAE;EAEnC;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;EAQE,MAAMH,KAAK,GAAG,IAAAC,cAAiB,EAAC,qEAAqE,CAAC;EACtG,MAAMG,SAAS,GAAGJ,KAAK,CAACK,MAAM,CAAC,MAAM,CAAC;EACtC;;EAEAL,KAAK,CAAE,iCAAgC,CAAC;EAExC,MAAMM,KAAK,GAAGH,MAAM,CAACI,GAAG,CAAC,KAAK,CAAC;EAC/BH,SAAS,CAAE,eAAcE,KAAK,CAACE,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CACtH5B,GAAG,CAAC,CAAC;MAAC4B;IAAK,CAAC,KAAKT,MAAM,CAACS,KAAK,CAAC,CAAC;EACpC;AACF"}
|
package/dist/index.js
CHANGED
|
@@ -63,14 +63,17 @@ var _default = ({
|
|
|
63
63
|
debugData(`ReturnNonMatches: ${JSON.stringify(returnNonMatches)}`);
|
|
64
64
|
debugData(`ReturnFailures: ${JSON.stringify(returnFailures)}`);
|
|
65
65
|
const detect = (0, _matchDetection.default)(detectionOptions, returnStrategy);
|
|
66
|
-
return
|
|
66
|
+
return prepareSearch;
|
|
67
|
+
async function prepareSearch({
|
|
67
68
|
record,
|
|
68
69
|
recordExternal = {
|
|
69
70
|
recordSource: 'incomingRecord',
|
|
70
71
|
label: 'ic'
|
|
71
72
|
}
|
|
72
|
-
})
|
|
73
|
-
const
|
|
73
|
+
}) {
|
|
74
|
+
const {
|
|
75
|
+
search
|
|
76
|
+
} = await (0, _candidateSearch.default)({
|
|
74
77
|
...searchOptions,
|
|
75
78
|
record,
|
|
76
79
|
maxCandidates,
|
|
@@ -573,7 +576,7 @@ var _default = ({
|
|
|
573
576
|
return true;
|
|
574
577
|
}
|
|
575
578
|
}
|
|
576
|
-
}
|
|
579
|
+
}
|
|
577
580
|
};
|
|
578
581
|
exports.default = _default;
|
|
579
582
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_debug","_interopRequireDefault","require","_candidateSearch","_interopRequireWildcard","candidateSearch","exports","_matchDetection","matchDetection","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","prototype","hasOwnProperty","call","i","set","obj","_default","detection","detectionOptions","search","searchOptions","maxMatches","maxCandidates","returnStrategy","returnQuery","returnNonMatches","returnFailures","debug","createDebugLogger","debugData","extend","JSON","stringify","detect","createDetectionInterface","record","recordExternal","recordSource","label","createSearchInterface","iterate","initialState","matches","candidateCount","nonMatches","duplicateCount","nonMatchCount","conversionFailures","matchErrors","records","failures","state","length","recordSetSize","failureSetSize","newCandidateCount","newConversionFailures","concat","handleRecordSet","queriesLeft","searchCounter","query","returnResult","stopReason","matchResult","iterateRecords","newDuplicateCount","newNonMatchCount","newMatches","newNonMatches","newMatchErrors","handleMatchResult","maxMatchesFound","maxCandidatesRetrieved","addQuery","map","match","matchQuery","conversionFailureCount","matchErrorCount","checkCounts","matchStatus","getMatchState","matchesResult","result","matchCount","chosenNonMatchCount","totalHandled","conversionFailuresCount","resultSetOffset","totalRecords","queryCandidateCounter","maxedQueries","searchesLeft","nonRetrieved","maxedQueriesStopReason","undefined","conversionFailuresStopReason","matchErrorsStopReason","newStopReason","status","recordMatches","recordNonMatches","recordCount","recordDuplicateCount","recordNonMatchCount","recordMatchErrors","candidate","newRecordCount","candidateNotInMatches","candidateRecord","id","candidateId","recordBExternal","detectionResult","recordA","recordB","recordAExternal","handleDetectionResult","error","matchError","payload","message","newRecordMatchErrors","slice","strategy","treshold","probability","strategyResult","newMatch","handleRecordMatch","newRecordNonMatchCount","isMatch","newRecordMatches","newRecordNonMatches","newCandidateId","find"],"sources":["../src/index.js"],"sourcesContent":["/**\n*\n* @licstart The following is the entire license notice for the JavaScript code in this file.\n*\n* Melinda record matching modules for Javascript\n*\n* Copyright (C) 2020-2022 University Of Helsinki (The National Library Of Finland)\n*\n* This file is part of melinda-record-matching-js\n*\n* melinda-record-matching-js program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Lesser General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* melinda-record-matching-js is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n*\n* @licend The above is the entire license notice\n* for the JavaScript code in this file.\n*\n*/\n\nimport createDebugLogger from 'debug';\nimport createSearchInterface, * as candidateSearch from './candidate-search';\nimport createDetectionInterface, * as matchDetection from './match-detection';\n//import inspect from 'util';\n\nexport {candidateSearch, matchDetection};\n\nexport default ({detection: detectionOptions, search: searchOptions, maxMatches = 1, maxCandidates = 25, returnStrategy = false, returnQuery = false, returnNonMatches = false, returnFailures = false}) => {\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:index');\n const debugData = debug.extend('data');\n\n debugData(`DetectionOptions: ${JSON.stringify(detectionOptions)}`);\n debugData(`SearchOptions: ${JSON.stringify(searchOptions)}`);\n debugData(`MaxMatches: ${JSON.stringify(maxMatches)}`);\n debugData(`MaxCandidates: ${JSON.stringify(maxCandidates)}`);\n debugData(`ReturnStrategy: ${JSON.stringify(returnStrategy)}`);\n debugData(`ReturnQuery: ${JSON.stringify(returnQuery)}`);\n debugData(`ReturnNonMatches: ${JSON.stringify(returnNonMatches)}`);\n debugData(`ReturnFailures: ${JSON.stringify(returnFailures)}`);\n\n\n const detect = createDetectionInterface(detectionOptions, returnStrategy);\n\n return ({record, recordExternal = {recordSource: 'incomingRecord', label: 'ic'}}) => {\n\n const search = createSearchInterface({...searchOptions, record, maxCandidates, recordExternal});\n return iterate({});\n\n // candidateCount : amount of candidate records retrived from SRU for matching, NOT including current record set\n // matches : candidates that have been detected as matches by current matcher job\n // nonMatches : candidates that have been detected as non-matches by current matcher job (only if returnNonMatches is 'true')\n // duplicateCount : amount of candidate records that were retrieved from the SRU but not handled further because they were already found in the matches/nonMatches\n\n // state.totalRecords : amount of candidate records available to the current query (undefined, if there was no queries left)\n // state.query : current query (undefined if there was no queries left)\n // state.searchCounter : sequence for current search for current query (undefined, if there we no queries left)\n // 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)\n // state.queriesLeft : amount of queries left\n // state.queryCounter : sequence for current query\n // state.maxedQueries : queries that resulted in more than serverMaxResults hits\n\n async function iterate({initialState = {}, matches = [], candidateCount = 0, nonMatches = [], duplicateCount = 0, nonMatchCount = 0, conversionFailures = [], matchErrors = []}) {\n debugData(`Starting next matcher iteration.`);\n const {records, failures, ...state} = await search(initialState);\n\n debugData(`Current state: ${JSON.stringify(state)}, matches: ${matches.length}, candidateCount: ${candidateCount}, nonMatches: ${nonMatches.length}, nonMatchCount: ${nonMatchCount}, conversionFailures: ${conversionFailures}, matchErrors: ${matchErrors.length}`);\n const recordSetSize = records.length;\n const failureSetSize = failures.length;\n const newCandidateCount = candidateCount + recordSetSize + failureSetSize;\n\n const newConversionFailures = conversionFailures.concat(failures);\n debugData(`Failures: ${failures.length}, ConversionFailures: ${conversionFailures.length}, NewConversionFailures: ${newConversionFailures.length}`);\n\n if (recordSetSize > 0) {\n return handleRecordSet();\n }\n\n if (state.queriesLeft > 0) {\n debug(`Empty record set ${state.searchCounter} for ${state.query}, but there are ${state.queriesLeft} queries left`);\n return iterate({initialState: state, matches, candidateCount: newCandidateCount, nonMatches, nonMatchCount, duplicateCount, conversionFailures: newConversionFailures, matchErrors});\n }\n\n debug(`No (more) candidate records to check, no more queries left, matches: ${matches.length}`);\n return returnResult({matches, state, stopReason: '', nonMatches, nonMatchCount, candidateCount: newCandidateCount, duplicateCount, conversionFailures: newConversionFailures, matchErrors});\n\n function handleRecordSet() {\n debug(`Checking record set of ${recordSetSize} candidate records for possible matches, found by ${state.searchCounter} search for ${state.query}`);\n\n const matchResult = iterateRecords({records, recordSetSize, maxMatches, matches, nonMatches, nonMatchCount});\n\n const newDuplicateCount = duplicateCount + matchResult.duplicateCount;\n const newNonMatchCount = nonMatchCount + matchResult.nonMatchCount;\n const {newMatches, newNonMatches, newMatchErrors} = handleMatchResult(matchResult, matches, nonMatches, matchErrors);\n\n if (maxMatchesFound({matches: newMatches, maxMatches})) {\n return returnResult({matches: newMatches, state, stopReason: 'maxMatches', nonMatches: newNonMatches, duplicateCount: newDuplicateCount, candidateCount: newCandidateCount, nonMatchCount: newNonMatchCount, conversionFailures: newConversionFailures, matchErrors: newMatchErrors});\n }\n\n if (maxCandidatesRetrieved(newCandidateCount, maxCandidates)) {\n return returnResult({matches: newMatches, state, stopReason: 'maxCandidates', nonMatches: newNonMatches, duplicateCount: newDuplicateCount, candidateCount: newCandidateCount, nonMatchCount: newNonMatchCount, conversionFailures: newConversionFailures, matchErrors: newMatchErrors});\n }\n\n return iterate({initialState: state, matches: newMatches, candidateCount: newCandidateCount, nonMatches: newNonMatches, duplicateCount: newDuplicateCount, nonMatchCount: newNonMatchCount, conversionFailures: newConversionFailures, matchErrors: newMatchErrors});\n }\n\n function handleMatchResult(matchResult, matches, nonMatches, matchErrors) {\n debugData(`- Amount of new matches from record set: ${matchResult.matches.length}`);\n // eslint-disable-next-line functional/no-conditional-statements\n if (returnNonMatches) {\n debugData(`- Amount of new nonMatches from record set: ${matchResult.nonMatches.length}`);\n }\n\n const newMatches = matches.concat(returnQuery ? addQuery(matchResult.matches) : matchResult.matches);\n const newNonMatches = returnNonMatches ? nonMatches.concat(returnQuery ? addQuery(matchResult.nonMatches) : matchResult.nonMatches) : [];\n const newMatchErrors = matchErrors.concat(matchResult.matchErrors);\n\n debugData(`- Total amount of matches: ${newMatches.length}`);\n // eslint-disable-next-line functional/no-conditional-statements\n if (returnNonMatches) {\n debugData(`- Total amount of nonMatches: ${newNonMatches.length}`);\n }\n\n debugData(`MatchResult: ${JSON.stringify(matchResult)}`);\n debugData(`Old matchErrors: ${JSON.stringify(matchErrors)}, matchErrors from matchResult: ${JSON.stringify(matchResult.matchErrors)}, New matchErrors: ${JSON.stringify(newMatchErrors)}`);\n\n debugData(`- Total amount of matchErrors: ${newMatchErrors.length}`);\n\n return {newMatches, newNonMatches, newMatchErrors};\n }\n\n function addQuery(matches) {\n debugData(`Adding query ${state.query} to matches`);\n return matches.map((match) => ({...match, matchQuery: state.query}));\n }\n\n function maxCandidatesRetrieved(candidateCount, maxCandidates) {\n debugData(`Total amount of candidate records retrieved: ${newCandidateCount} (max: ${maxCandidates})`);\n if (maxCandidates && candidateCount >= maxCandidates) {\n debug(`Stopped matching because maximum number of candidate records ${candidateCount} / ${maxCandidates} have been retrieved`);\n return true;\n }\n }\n }\n\n // matches : array of matching candidate records\n // nonMatches : array of nonMatching candidate records (if returnNonMatches option is true, otherwise empty array)\n // - candidate.id\n // - candidate.record\n // - probability\n // - strategy (if returnStrategy option is true)\n // - treshold (if returnStrategy option is true)\n // - matchQuery (if returnQuery option is true)\n // failures: array of conversionFailures from candidate-search and matchErrors from matchDetection in error format {status, payload: {message, id}} if returnFailures is true\n\n // we could have here also returnRecords/returnMatchRecords/returnNonMatchRecord options that could be turned false for not to return actual record data\n\n // matchStatus.status: boolean, true if matcher retrieved and handled all found candidate records, false if it did not\n // matchStatus.stopReason: string ('maxMatches','maxCandidates','maxedQueries','conversionFailures', empty string/undefined), reason for stopping retrieving or handling the candidate records\n // - only one stopReason is returned (if there would be several possible stopReasons, stopReason is picked in the above order)\n // - 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\n\n function returnResult({matches, state, stopReason, nonMatches, duplicateCount, candidateCount, nonMatchCount, conversionFailures, matchErrors}) {\n const conversionFailureCount = conversionFailures.length;\n const matchErrorCount = matchErrors.length;\n checkCounts({matches, nonMatches, candidateCount, duplicateCount, nonMatchCount, conversionFailureCount, matchErrorCount});\n const matchStatus = getMatchState(state, stopReason, conversionFailureCount, matchErrorCount);\n // add nonMatches to result only if returnNonMatches is 'true', otherwise nonMatches have not been gathered\n const matchesResult = returnNonMatches ? {matches, matchStatus, nonMatches, candidateCount} : {matches, matchStatus, candidateCount};\n const failures = [...conversionFailures, ...matchErrors];\n const result = returnFailures ? {...matchesResult, conversionFailures: failures} : matchesResult;\n debugData(`ReturnFailures ${returnFailures}`);\n debugData(`${JSON.stringify(result)}`);\n return result;\n\n // note that in cases where the matching has been stopped because of maxMatches checkCounts won't (in most cases) match\n\n function checkCounts({matches, nonMatches, candidateCount, duplicateCount, nonMatchCount, conversionFailureCount, matchErrorCount}) {\n const matchCount = matches.length;\n debugData(`Return nonMatches: ${returnNonMatches}`);\n const chosenNonMatchCount = returnNonMatches ? nonMatches.length : nonMatchCount;\n const totalHandled = matchCount + chosenNonMatchCount + duplicateCount;\n debug(`candidateCount: ${candidateCount}, matches: ${matchCount}, nonMatches: ${chosenNonMatchCount}, duplicateCount: ${duplicateCount}, conversionFailureCount: ${conversionFailureCount}, matchErrorCount: ${matchErrorCount}`);\n debug(`We got result for ${totalHandled} / ${candidateCount} retrieved candidates`);\n if (totalHandled !== candidateCount) {\n debug(`WARNING: Missing results for ${candidateCount - totalHandled} candidates`);\n return;\n }\n return;\n }\n\n // eslint-disable-next-line max-statements\n function getMatchState(state, stopReason, conversionFailuresCount, matchErrorCount) {\n debugData(`${JSON.stringify(state)}`);\n debug(`We had ${conversionFailuresCount} retrieved candidates that could not be converted.`);\n debug(`We had ${matchErrorCount} retrieved candidates that errored in matchDetection.`);\n 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}`);\n\n debugData(`StopReason: <${stopReason}>`);\n\n const searchesLeft = state.resultSetOffset && state.resultSetOffset <= state.totalRecords;\n const nonRetrieved = searchesLeft ? state.totalRecords - state.queryCandidateCounter : 0;\n debugData(`nonRetrieved: ${nonRetrieved}`);\n\n // matchStatus.stopReason: string ('maxMatches','maxCandidates','maxedQueries','conversionFailures', empty string/undefined), reason for stopping retrieving or handling the candidate records\n // 'maxMatches' and 'maxCandidates' are in stopReason, 'maxedQueries', 'conversionFailures' and 'matchErrors' are created here\n\n if (state.queriesLeft > 0 || nonRetrieved > 0 || state.maxedQueries.length > 0 || conversionFailureCount > 0 || matchErrorCount > 0) {\n const maxedQueriesStopReason = state.maxedQueries.length > 0 ? 'maxedQueries' : undefined;\n const conversionFailuresStopReason = conversionFailureCount > 0 ? 'conversionFailures' : undefined;\n const matchErrorsStopReason = matchErrorCount > 0 ? 'matchErrors' : undefined;\n const newStopReason = stopReason === '' || stopReason === undefined ? maxedQueriesStopReason || conversionFailuresStopReason || matchErrorsStopReason : stopReason;\n debugData(`MaxedQueriesStopReason: <${maxedQueriesStopReason}>`);\n debugData(`ConversionFailureStopReason <${conversionFailuresStopReason}>`);\n debugData(`MatchErrorsStopReason <${matchErrorsStopReason}>`);\n debugData(`NewStopReason: <${newStopReason}>`);\n debug(`Match status: false`);\n return {status: false, stopReason: newStopReason};\n }\n\n debug(`Match status: true`);\n return {status: true, stopReason};\n }\n }\n\n // NOTES:\n // - we could optimize by creating the featureSet for the incoming record once and using it for all database/candidateRecords\n // - if creating the featureSet for the incoming record fails we have an unprocessable entity\n // - if creating the featureSet for a candidate record fails we could skip that candidate - but list the case as a detectionFailure, same as conversionFailures\n\n function iterateRecords({records, recordSetSize, maxMatches, matches = [], nonMatches = [], recordMatches = [], recordNonMatches = [], recordCount = 0, recordDuplicateCount = 0, recordNonMatchCount = 0, recordMatchErrors = []}) {\n\n // recordSetSize : total amount of records in the current record set\n // recordCount : amount of records from the current record set that have been handled\n // maxMatches : setting for maximum amount found by current matcher job before the matcher job is stopped\n // recordDuplicateCount : amount of records from the current record set that are already included in matches/nonMatches results\n // recordNonMatchCount: amount of records from the current record set that are nonMatches (only is returnNonMatches setting is false)\n\n // records : non-handled records in the current record set\n // matches : found matches in the current matcher job\n // recordMatches : found matches in the current record set\n // recordNonMatches : found nonMatches in the current record set (only if returnNonMatches setting is true)\n // recordMatchErrors: errored matchDetection in the current record set\n\n const [candidate] = records;\n const newRecordCount = candidate ? recordCount + 1 : recordCount;\n\n // The matcher uses same matchDetection strategy for candidates from all candidate-searches -> matchDetection result for the same candidate is always same\n // Exceptions would happen if the candidate would have been updated in the database between candidate searches\n // 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\n // different candidate search queries. Same candidate search query won't have duplicate records.\n\n /* We could optimize and detect all retrieved candidates at once\n const candidateRecords = records.map(record => record.record);\n const recordsIsArray = Array.isArray(candidateRecords);\n debug(`records is an array: ${recordsIsArray}`);\n const result = detect(record, candidateRecords);\n debugData(`${JSON.stringify(result)}`);\n */\n\n if (candidate) {\n\n // eslint-disable-next-line functional/no-conditional-statements\n if (candidateNotInMatches(matches.concat(nonMatches), candidate)) {\n const {record: candidateRecord, id: candidateId} = candidate;\n const recordBExternal = {id: candidate.id, recordSource: 'databaseRecord', label: `db-${candidate.id}`};\n try {\n debug(`Running matchDetection for record ${candidateId} (${newRecordCount}/${recordSetSize})`);\n // we should handle errors from detection somehow - ie. cases where either record or candidateRecord errors\n const detectionResult = detect({recordA: record, recordB: candidateRecord, recordAExternal: recordExternal, recordBExternal});\n\n return handleDetectionResult(detectionResult, candidateId, candidateRecord);\n } catch (error) {\n debug(`MatchDetection errored: database record ${candidateId}: ${error}`);\n\n const matchError = {status: 422, payload: {message: `Matching errored for database record ${candidateId}. ${error.message}.`, id: candidateId}};\n const newRecordMatchErrors = recordMatchErrors.concat(matchError);\n return iterateRecords({records: records.slice(1), recordSetSize, maxMatches, matches, recordMatches, recordCount: newRecordCount, recordNonMatches, recordDuplicateCount, recordNonMatchCount, recordMatchErrors: newRecordMatchErrors});\n }\n }\n\n return iterateRecords({records: records.slice(1), recordSetSize, maxMatches, matches, recordMatches, recordCount: newRecordCount, recordNonMatches, recordDuplicateCount: recordDuplicateCount + 1, recordNonMatchCount, recordMatchErrors});\n }\n\n debug(`No more candidates, record set (${recordCount}/${recordSetSize}) done, ${recordMatches.length} matches found, ${recordDuplicateCount} candidates already handled, ${returnNonMatches ? `${recordNonMatches.length}` : `${recordNonMatchCount}`} nonMatches found.`);\n return {matches: recordMatches, nonMatches: returnNonMatches ? recordNonMatches : [], duplicateCount: recordDuplicateCount, nonMatchCount: recordNonMatchCount, matchErrors: recordMatchErrors};\n\n function handleDetectionResult(detectionResult, candidateId, candidateRecord) {\n debugData(`MatchDetection results for ${candidateId} (${newRecordCount}/${recordSetSize}): ${JSON.stringify(detectionResult)}`);\n\n if (detectionResult.match || returnNonMatches) {\n debug(`${detectionResult.match ? `Record ${candidateId} (${newRecordCount}/${recordSetSize}) is a match!` : `Record ${candidateId} (${newRecordCount}/${recordSetSize}) is NOT a match!`}`);\n debugData(`Strategy: ${JSON.stringify(detectionResult.strategy)}, Treshold: ${JSON.stringify(detectionResult.treshold)}`);\n\n const matchResult = {\n probability: detectionResult.probability,\n candidate: {\n id: candidateId,\n record: candidateRecord\n }\n };\n const strategyResult = {\n strategy: detectionResult.strategy,\n treshold: detectionResult.treshold\n };\n const newMatch = returnStrategy ? {...matchResult, ...strategyResult} : {...matchResult};\n\n debugData(`${JSON.stringify(newMatch)}`);\n\n return handleRecordMatch(detectionResult.match, newMatch);\n }\n\n const newRecordNonMatchCount = recordNonMatchCount + 1;\n debugData(`- Total nonMatches after this detection: ${newRecordNonMatchCount}`);\n\n return iterateRecords({records: records.slice(1), recordSetSize, maxMatches, matches, recordMatches, recordCount: newRecordCount, recordNonMatches, recordDuplicateCount, recordNonMatchCount: newRecordNonMatchCount, recordMatchErrors});\n }\n\n function handleRecordMatch(isMatch, newMatch) {\n const newRecordMatches = isMatch ? recordMatches.concat(newMatch) : recordMatches;\n const newRecordNonMatches = isMatch ? recordNonMatches : recordNonMatches.concat(newMatch);\n const newRecordNonMatchCount = isMatch ? recordNonMatchCount : recordNonMatchCount + 1;\n\n debugData(`- Total matches after this detection: ${matches.concat(newRecordMatches).length} (max: ${maxMatches})`);\n\n // eslint-disable-next-line functional/no-conditional-statements\n if (returnNonMatches) {\n debugData(`- Total nonMatches after this detection: ${nonMatches.concat(newRecordNonMatches).length}`);\n }\n debugData(`- Total nonMatchCount after this detection: ${recordNonMatchCount}`);\n\n if (maxMatchesFound({matches: matches.concat(newRecordMatches), maxMatches})) {\n debug(`MaxMatches (${maxMatches}) reached, handled candidates in record set: ${newRecordCount} non-handled candidates in record set ${recordSetSize - newRecordCount}`);\n return {matches: newRecordMatches, nonMatches: returnNonMatches ? newRecordNonMatches : [], duplicateCount: recordDuplicateCount, nonMatchCount: newRecordNonMatchCount, matchErrors: recordMatchErrors};\n }\n\n return iterateRecords({records: records.slice(1), recordSetSize, maxMatches, matches, recordMatches: newRecordMatches, recordCount: newRecordCount, recordNonMatches: returnNonMatches ? newRecordNonMatches : [], duplicateCount: recordDuplicateCount, recordNonMatchCount: newRecordNonMatchCount, matchErrors: recordMatchErrors});\n }\n\n function candidateNotInMatches(matches, candidate) {\n debug(`Checking that record ${candidate.id} is not already included in ${matches.length} matches/nonMatches`);\n const newCandidateId = candidate.id;\n debugData(`newCandidateId: ${newCandidateId}`);\n const result = matches.find(({candidate}) => candidate.id === newCandidateId);\n debugData(`Result: ${result}`);\n if (result) {\n debug(`${candidate.id} was already handled.`);\n return false;\n }\n debug(`${candidate.id} not found in matches/nonMatches`);\n return true;\n }\n }\n\n function maxMatchesFound({matches, maxMatches}) {\n if (maxMatches && matches.length >= maxMatches) {\n debug(`Stopping recordSet iteration: maxMatches (${maxMatches}) for matcher job found.`);\n return true;\n }\n }\n };\n};\n"],"mappings":";;;;;;AA4BA,IAAAA,MAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,gBAAA,GAAAC,uBAAA,CAAAF,OAAA;AAA6E,IAAAG,eAAA,GAAAF,gBAAA;AAAAG,OAAA,CAAAD,eAAA,GAAAF,gBAAA;AAC7E,IAAAI,eAAA,GAAAH,uBAAA,CAAAF,OAAA;AAA8E,IAAAM,cAAA,GAAAD,eAAA;AAAAD,OAAA,CAAAE,cAAA,GAAAD,eAAA;AAAA,SAAAE,yBAAAC,CAAA,6BAAAC,OAAA,mBAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,CAAA,WAAAA,CAAA,GAAAG,CAAA,GAAAD,CAAA,KAAAF,CAAA;AAAA,SAAAN,wBAAAM,CAAA,EAAAE,CAAA,SAAAA,CAA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AK,CAAE,6CAA4CN,UAAW,0BAAyB,CAAC;QACxF,OAAO,IAAI;MACb;IACF;EACF,CAAC;AACH,CAAC;AAAA9B,OAAA,CAAAS,OAAA,GAAAgB,QAAA"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["_debug","_interopRequireDefault","require","_candidateSearch","_interopRequireWildcard","candidateSearch","exports","_matchDetection","matchDetection","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","prototype","hasOwnProperty","call","i","set","obj","_default","detection","detectionOptions","search","searchOptions","maxMatches","maxCandidates","returnStrategy","returnQuery","returnNonMatches","returnFailures","debug","createDebugLogger","debugData","extend","JSON","stringify","detect","createDetectionInterface","prepareSearch","record","recordExternal","recordSource","label","createSearchInterface","iterate","initialState","matches","candidateCount","nonMatches","duplicateCount","nonMatchCount","conversionFailures","matchErrors","records","failures","state","length","recordSetSize","failureSetSize","newCandidateCount","newConversionFailures","concat","handleRecordSet","queriesLeft","searchCounter","query","returnResult","stopReason","matchResult","iterateRecords","newDuplicateCount","newNonMatchCount","newMatches","newNonMatches","newMatchErrors","handleMatchResult","maxMatchesFound","maxCandidatesRetrieved","addQuery","map","match","matchQuery","conversionFailureCount","matchErrorCount","checkCounts","matchStatus","getMatchState","matchesResult","result","matchCount","chosenNonMatchCount","totalHandled","conversionFailuresCount","resultSetOffset","totalRecords","queryCandidateCounter","maxedQueries","searchesLeft","nonRetrieved","maxedQueriesStopReason","undefined","conversionFailuresStopReason","matchErrorsStopReason","newStopReason","status","recordMatches","recordNonMatches","recordCount","recordDuplicateCount","recordNonMatchCount","recordMatchErrors","candidate","newRecordCount","candidateNotInMatches","candidateRecord","id","candidateId","recordBExternal","detectionResult","recordA","recordB","recordAExternal","handleDetectionResult","error","matchError","payload","message","newRecordMatchErrors","slice","strategy","treshold","probability","strategyResult","newMatch","handleRecordMatch","newRecordNonMatchCount","isMatch","newRecordMatches","newRecordNonMatches","newCandidateId","find"],"sources":["../src/index.js"],"sourcesContent":["/**\n*\n* @licstart The following is the entire license notice for the JavaScript code in this file.\n*\n* Melinda record matching modules for Javascript\n*\n* Copyright (C) 2020-2022 University Of Helsinki (The National Library Of Finland)\n*\n* This file is part of melinda-record-matching-js\n*\n* melinda-record-matching-js program is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Lesser General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* melinda-record-matching-js is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see <http://www.gnu.org/licenses/>.\n*\n* @licend The above is the entire license notice\n* for the JavaScript code in this file.\n*\n*/\n\nimport createDebugLogger from 'debug';\nimport createSearchInterface, * as candidateSearch from './candidate-search';\nimport createDetectionInterface, * as matchDetection from './match-detection';\n//import inspect from 'util';\n\nexport {candidateSearch, matchDetection};\n\nexport default ({detection: detectionOptions, search: searchOptions, maxMatches = 1, maxCandidates = 25, returnStrategy = false, returnQuery = false, returnNonMatches = false, returnFailures = false}) => {\n const debug = createDebugLogger('@natlibfi/melinda-record-matching:index');\n const debugData = debug.extend('data');\n\n debugData(`DetectionOptions: ${JSON.stringify(detectionOptions)}`);\n debugData(`SearchOptions: ${JSON.stringify(searchOptions)}`);\n debugData(`MaxMatches: ${JSON.stringify(maxMatches)}`);\n debugData(`MaxCandidates: ${JSON.stringify(maxCandidates)}`);\n debugData(`ReturnStrategy: ${JSON.stringify(returnStrategy)}`);\n debugData(`ReturnQuery: ${JSON.stringify(returnQuery)}`);\n debugData(`ReturnNonMatches: ${JSON.stringify(returnNonMatches)}`);\n debugData(`ReturnFailures: ${JSON.stringify(returnFailures)}`);\n\n\n const detect = createDetectionInterface(detectionOptions, returnStrategy);\n\n return prepareSearch;\n\n async function prepareSearch({record, recordExternal = {recordSource: 'incomingRecord', label: 'ic'}}) {\n\n const {search} = await createSearchInterface({...searchOptions, record, maxCandidates, recordExternal});\n return iterate({});\n\n // candidateCount : amount of candidate records retrived from SRU for matching, NOT including current record set\n // matches : candidates that have been detected as matches by current matcher job\n // nonMatches : candidates that have been detected as non-matches by current matcher job (only if returnNonMatches is 'true')\n // duplicateCount : amount of candidate records that were retrieved from the SRU but not handled further because they were already found in the matches/nonMatches\n\n // state.totalRecords : amount of candidate records available to the current query (undefined, if there was no queries left)\n // state.query : current query (undefined if there was no queries left)\n // state.searchCounter : sequence for current search for current query (undefined, if there we no queries left)\n // 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)\n // state.queriesLeft : amount of queries left\n // state.queryCounter : sequence for current query\n // state.maxedQueries : queries that resulted in more than serverMaxResults hits\n\n async function iterate({initialState = {}, matches = [], candidateCount = 0, nonMatches = [], duplicateCount = 0, nonMatchCount = 0, conversionFailures = [], matchErrors = []}) {\n debugData(`Starting next matcher iteration.`);\n const {records, failures, ...state} = await search(initialState);\n\n debugData(`Current state: ${JSON.stringify(state)}, matches: ${matches.length}, candidateCount: ${candidateCount}, nonMatches: ${nonMatches.length}, nonMatchCount: ${nonMatchCount}, conversionFailures: ${conversionFailures}, matchErrors: ${matchErrors.length}`);\n const recordSetSize = records.length;\n const failureSetSize = failures.length;\n const newCandidateCount = candidateCount + recordSetSize + failureSetSize;\n\n const newConversionFailures = conversionFailures.concat(failures);\n debugData(`Failures: ${failures.length}, ConversionFailures: ${conversionFailures.length}, NewConversionFailures: ${newConversionFailures.length}`);\n\n if (recordSetSize > 0) {\n return handleRecordSet();\n }\n\n if (state.queriesLeft > 0) {\n debug(`Empty record set ${state.searchCounter} for ${state.query}, but there are ${state.queriesLeft} queries left`);\n return iterate({initialState: state, matches, candidateCount: newCandidateCount, nonMatches, nonMatchCount, duplicateCount, conversionFailures: newConversionFailures, matchErrors});\n }\n\n debug(`No (more) candidate records to check, no more queries left, matches: ${matches.length}`);\n return returnResult({matches, state, stopReason: '', nonMatches, nonMatchCount, candidateCount: newCandidateCount, duplicateCount, conversionFailures: newConversionFailures, matchErrors});\n\n function handleRecordSet() {\n debug(`Checking record set of ${recordSetSize} candidate records for possible matches, found by ${state.searchCounter} search for ${state.query}`);\n\n const matchResult = iterateRecords({records, recordSetSize, maxMatches, matches, nonMatches, nonMatchCount});\n\n const newDuplicateCount = duplicateCount + matchResult.duplicateCount;\n const newNonMatchCount = nonMatchCount + matchResult.nonMatchCount;\n const {newMatches, newNonMatches, newMatchErrors} = handleMatchResult(matchResult, matches, nonMatches, matchErrors);\n\n if (maxMatchesFound({matches: newMatches, maxMatches})) {\n return returnResult({matches: newMatches, state, stopReason: 'maxMatches', nonMatches: newNonMatches, duplicateCount: newDuplicateCount, candidateCount: newCandidateCount, nonMatchCount: newNonMatchCount, conversionFailures: newConversionFailures, matchErrors: newMatchErrors});\n }\n\n if (maxCandidatesRetrieved(newCandidateCount, maxCandidates)) {\n return returnResult({matches: newMatches, state, stopReason: 'maxCandidates', nonMatches: newNonMatches, duplicateCount: newDuplicateCount, candidateCount: newCandidateCount, nonMatchCount: newNonMatchCount, conversionFailures: newConversionFailures, matchErrors: newMatchErrors});\n }\n\n return iterate({initialState: state, matches: newMatches, candidateCount: newCandidateCount, nonMatches: newNonMatches, duplicateCount: newDuplicateCount, nonMatchCount: newNonMatchCount, conversionFailures: newConversionFailures, matchErrors: newMatchErrors});\n }\n\n function handleMatchResult(matchResult, matches, nonMatches, matchErrors) {\n debugData(`- Amount of new matches from record set: ${matchResult.matches.length}`);\n // eslint-disable-next-line functional/no-conditional-statements\n if (returnNonMatches) {\n debugData(`- Amount of new nonMatches from record set: ${matchResult.nonMatches.length}`);\n }\n\n const newMatches = matches.concat(returnQuery ? addQuery(matchResult.matches) : matchResult.matches);\n const newNonMatches = returnNonMatches ? nonMatches.concat(returnQuery ? addQuery(matchResult.nonMatches) : matchResult.nonMatches) : [];\n const newMatchErrors = matchErrors.concat(matchResult.matchErrors);\n\n debugData(`- Total amount of matches: ${newMatches.length}`);\n // eslint-disable-next-line functional/no-conditional-statements\n if (returnNonMatches) {\n debugData(`- Total amount of nonMatches: ${newNonMatches.length}`);\n }\n\n debugData(`MatchResult: ${JSON.stringify(matchResult)}`);\n debugData(`Old matchErrors: ${JSON.stringify(matchErrors)}, matchErrors from matchResult: ${JSON.stringify(matchResult.matchErrors)}, New matchErrors: ${JSON.stringify(newMatchErrors)}`);\n\n debugData(`- Total amount of matchErrors: ${newMatchErrors.length}`);\n\n return {newMatches, newNonMatches, newMatchErrors};\n }\n\n function addQuery(matches) {\n debugData(`Adding query ${state.query} to matches`);\n return matches.map((match) => ({...match, matchQuery: state.query}));\n }\n\n function maxCandidatesRetrieved(candidateCount, maxCandidates) {\n debugData(`Total amount of candidate records retrieved: ${newCandidateCount} (max: ${maxCandidates})`);\n if (maxCandidates && candidateCount >= maxCandidates) {\n debug(`Stopped matching because maximum number of candidate records ${candidateCount} / ${maxCandidates} have been retrieved`);\n return true;\n }\n }\n }\n\n // matches : array of matching candidate records\n // nonMatches : array of nonMatching candidate records (if returnNonMatches option is true, otherwise empty array)\n // - candidate.id\n // - candidate.record\n // - probability\n // - strategy (if returnStrategy option is true)\n // - treshold (if returnStrategy option is true)\n // - matchQuery (if returnQuery option is true)\n // failures: array of conversionFailures from candidate-search and matchErrors from matchDetection in error format {status, payload: {message, id}} if returnFailures is true\n\n // we could have here also returnRecords/returnMatchRecords/returnNonMatchRecord options that could be turned false for not to return actual record data\n\n // matchStatus.status: boolean, true if matcher retrieved and handled all found candidate records, false if it did not\n // matchStatus.stopReason: string ('maxMatches','maxCandidates','maxedQueries','conversionFailures', empty string/undefined), reason for stopping retrieving or handling the candidate records\n // - only one stopReason is returned (if there would be several possible stopReasons, stopReason is picked in the above order)\n // - 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\n\n function returnResult({matches, state, stopReason, nonMatches, duplicateCount, candidateCount, nonMatchCount, conversionFailures, matchErrors}) {\n const conversionFailureCount = conversionFailures.length;\n const matchErrorCount = matchErrors.length;\n checkCounts({matches, nonMatches, candidateCount, duplicateCount, nonMatchCount, conversionFailureCount, matchErrorCount});\n const matchStatus = getMatchState(state, stopReason, conversionFailureCount, matchErrorCount);\n // add nonMatches to result only if returnNonMatches is 'true', otherwise nonMatches have not been gathered\n const matchesResult = returnNonMatches ? {matches, matchStatus, nonMatches, candidateCount} : {matches, matchStatus, candidateCount};\n const failures = [...conversionFailures, ...matchErrors];\n const result = returnFailures ? {...matchesResult, conversionFailures: failures} : matchesResult;\n debugData(`ReturnFailures ${returnFailures}`);\n debugData(`${JSON.stringify(result)}`);\n return result;\n\n // note that in cases where the matching has been stopped because of maxMatches checkCounts won't (in most cases) match\n\n function checkCounts({matches, nonMatches, candidateCount, duplicateCount, nonMatchCount, conversionFailureCount, matchErrorCount}) {\n const matchCount = matches.length;\n debugData(`Return nonMatches: ${returnNonMatches}`);\n const chosenNonMatchCount = returnNonMatches ? nonMatches.length : nonMatchCount;\n const totalHandled = matchCount + chosenNonMatchCount + duplicateCount;\n debug(`candidateCount: ${candidateCount}, matches: ${matchCount}, nonMatches: ${chosenNonMatchCount}, duplicateCount: ${duplicateCount}, conversionFailureCount: ${conversionFailureCount}, matchErrorCount: ${matchErrorCount}`);\n debug(`We got result for ${totalHandled} / ${candidateCount} retrieved candidates`);\n if (totalHandled !== candidateCount) {\n debug(`WARNING: Missing results for ${candidateCount - totalHandled} candidates`);\n return;\n }\n return;\n }\n\n // eslint-disable-next-line max-statements\n function getMatchState(state, stopReason, conversionFailuresCount, matchErrorCount) {\n debugData(`${JSON.stringify(state)}`);\n debug(`We had ${conversionFailuresCount} retrieved candidates that could not be converted.`);\n debug(`We had ${matchErrorCount} retrieved candidates that errored in matchDetection.`);\n 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}`);\n\n debugData(`StopReason: <${stopReason}>`);\n\n const searchesLeft = state.resultSetOffset && state.resultSetOffset <= state.totalRecords;\n const nonRetrieved = searchesLeft ? state.totalRecords - state.queryCandidateCounter : 0;\n debugData(`nonRetrieved: ${nonRetrieved}`);\n\n // matchStatus.stopReason: string ('maxMatches','maxCandidates','maxedQueries','conversionFailures', empty string/undefined), reason for stopping retrieving or handling the candidate records\n // 'maxMatches' and 'maxCandidates' are in stopReason, 'maxedQueries', 'conversionFailures' and 'matchErrors' are created here\n\n if (state.queriesLeft > 0 || nonRetrieved > 0 || state.maxedQueries.length > 0 || conversionFailureCount > 0 || matchErrorCount > 0) {\n const maxedQueriesStopReason = state.maxedQueries.length > 0 ? 'maxedQueries' : undefined;\n const conversionFailuresStopReason = conversionFailureCount > 0 ? 'conversionFailures' : undefined;\n const matchErrorsStopReason = matchErrorCount > 0 ? 'matchErrors' : undefined;\n const newStopReason = stopReason === '' || stopReason === undefined ? maxedQueriesStopReason || conversionFailuresStopReason || matchErrorsStopReason : stopReason;\n debugData(`MaxedQueriesStopReason: <${maxedQueriesStopReason}>`);\n debugData(`ConversionFailureStopReason <${conversionFailuresStopReason}>`);\n debugData(`MatchErrorsStopReason <${matchErrorsStopReason}>`);\n debugData(`NewStopReason: <${newStopReason}>`);\n debug(`Match status: false`);\n return {status: false, stopReason: newStopReason};\n }\n\n debug(`Match status: true`);\n return {status: true, stopReason};\n }\n }\n\n // NOTES:\n // - we could optimize by creating the featureSet for the incoming record once and using it for all database/candidateRecords\n // - if creating the featureSet for the incoming record fails we have an unprocessable entity\n // - if creating the featureSet for a candidate record fails we could skip that candidate - but list the case as a detectionFailure, same as conversionFailures\n\n function iterateRecords({records, recordSetSize, maxMatches, matches = [], nonMatches = [], recordMatches = [], recordNonMatches = [], recordCount = 0, recordDuplicateCount = 0, recordNonMatchCount = 0, recordMatchErrors = []}) {\n\n // recordSetSize : total amount of records in the current record set\n // recordCount : amount of records from the current record set that have been handled\n // maxMatches : setting for maximum amount found by current matcher job before the matcher job is stopped\n // recordDuplicateCount : amount of records from the current record set that are already included in matches/nonMatches results\n // recordNonMatchCount: amount of records from the current record set that are nonMatches (only is returnNonMatches setting is false)\n\n // records : non-handled records in the current record set\n // matches : found matches in the current matcher job\n // recordMatches : found matches in the current record set\n // recordNonMatches : found nonMatches in the current record set (only if returnNonMatches setting is true)\n // recordMatchErrors: errored matchDetection in the current record set\n\n const [candidate] = records;\n const newRecordCount = candidate ? recordCount + 1 : recordCount;\n\n // The matcher uses same matchDetection strategy for candidates from all candidate-searches -> matchDetection result for the same candidate is always same\n // Exceptions would happen if the candidate would have been updated in the database between candidate searches\n // 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\n // different candidate search queries. Same candidate search query won't have duplicate records.\n\n /* We could optimize and detect all retrieved candidates at once\n const candidateRecords = records.map(record => record.record);\n const recordsIsArray = Array.isArray(candidateRecords);\n debug(`records is an array: ${recordsIsArray}`);\n const result = detect(record, candidateRecords);\n debugData(`${JSON.stringify(result)}`);\n */\n\n if (candidate) {\n\n // eslint-disable-next-line functional/no-conditional-statements\n if (candidateNotInMatches(matches.concat(nonMatches), candidate)) {\n const {record: candidateRecord, id: candidateId} = candidate;\n const recordBExternal = {id: candidate.id, recordSource: 'databaseRecord', label: `db-${candidate.id}`};\n try {\n debug(`Running matchDetection for record ${candidateId} (${newRecordCount}/${recordSetSize})`);\n // we should handle errors from detection somehow - ie. cases where either record or candidateRecord errors\n const detectionResult = detect({recordA: record, recordB: candidateRecord, recordAExternal: recordExternal, recordBExternal});\n\n return handleDetectionResult(detectionResult, candidateId, candidateRecord);\n } catch (error) {\n debug(`MatchDetection errored: database record ${candidateId}: ${error}`);\n\n const matchError = {status: 422, payload: {message: `Matching errored for database record ${candidateId}. ${error.message}.`, id: candidateId}};\n const newRecordMatchErrors = recordMatchErrors.concat(matchError);\n return iterateRecords({records: records.slice(1), recordSetSize, maxMatches, matches, recordMatches, recordCount: newRecordCount, recordNonMatches, recordDuplicateCount, recordNonMatchCount, recordMatchErrors: newRecordMatchErrors});\n }\n }\n\n return iterateRecords({records: records.slice(1), recordSetSize, maxMatches, matches, recordMatches, recordCount: newRecordCount, recordNonMatches, recordDuplicateCount: recordDuplicateCount + 1, recordNonMatchCount, recordMatchErrors});\n }\n\n debug(`No more candidates, record set (${recordCount}/${recordSetSize}) done, ${recordMatches.length} matches found, ${recordDuplicateCount} candidates already handled, ${returnNonMatches ? `${recordNonMatches.length}` : `${recordNonMatchCount}`} nonMatches found.`);\n return {matches: recordMatches, nonMatches: returnNonMatches ? recordNonMatches : [], duplicateCount: recordDuplicateCount, nonMatchCount: recordNonMatchCount, matchErrors: recordMatchErrors};\n\n function handleDetectionResult(detectionResult, candidateId, candidateRecord) {\n debugData(`MatchDetection results for ${candidateId} (${newRecordCount}/${recordSetSize}): ${JSON.stringify(detectionResult)}`);\n\n if (detectionResult.match || returnNonMatches) {\n debug(`${detectionResult.match ? `Record ${candidateId} (${newRecordCount}/${recordSetSize}) is a match!` : `Record ${candidateId} (${newRecordCount}/${recordSetSize}) is NOT a match!`}`);\n debugData(`Strategy: ${JSON.stringify(detectionResult.strategy)}, Treshold: ${JSON.stringify(detectionResult.treshold)}`);\n\n const matchResult = {\n probability: detectionResult.probability,\n candidate: {\n id: candidateId,\n record: candidateRecord\n }\n };\n const strategyResult = {\n strategy: detectionResult.strategy,\n treshold: detectionResult.treshold\n };\n const newMatch = returnStrategy ? {...matchResult, ...strategyResult} : {...matchResult};\n\n debugData(`${JSON.stringify(newMatch)}`);\n\n return handleRecordMatch(detectionResult.match, newMatch);\n }\n\n const newRecordNonMatchCount = recordNonMatchCount + 1;\n debugData(`- Total nonMatches after this detection: ${newRecordNonMatchCount}`);\n\n return iterateRecords({records: records.slice(1), recordSetSize, maxMatches, matches, recordMatches, recordCount: newRecordCount, recordNonMatches, recordDuplicateCount, recordNonMatchCount: newRecordNonMatchCount, recordMatchErrors});\n }\n\n function handleRecordMatch(isMatch, newMatch) {\n const newRecordMatches = isMatch ? recordMatches.concat(newMatch) : recordMatches;\n const newRecordNonMatches = isMatch ? recordNonMatches : recordNonMatches.concat(newMatch);\n const newRecordNonMatchCount = isMatch ? recordNonMatchCount : recordNonMatchCount + 1;\n\n debugData(`- Total matches after this detection: ${matches.concat(newRecordMatches).length} (max: ${maxMatches})`);\n\n // eslint-disable-next-line functional/no-conditional-statements\n if (returnNonMatches) {\n debugData(`- Total nonMatches after this detection: ${nonMatches.concat(newRecordNonMatches).length}`);\n }\n debugData(`- Total nonMatchCount after this detection: ${recordNonMatchCount}`);\n\n if (maxMatchesFound({matches: matches.concat(newRecordMatches), maxMatches})) {\n debug(`MaxMatches (${maxMatches}) reached, handled candidates in record set: ${newRecordCount} non-handled candidates in record set ${recordSetSize - newRecordCount}`);\n return {matches: newRecordMatches, nonMatches: returnNonMatches ? newRecordNonMatches : [], duplicateCount: recordDuplicateCount, nonMatchCount: newRecordNonMatchCount, matchErrors: recordMatchErrors};\n }\n\n return iterateRecords({records: records.slice(1), recordSetSize, maxMatches, matches, recordMatches: newRecordMatches, recordCount: newRecordCount, recordNonMatches: returnNonMatches ? newRecordNonMatches : [], duplicateCount: recordDuplicateCount, recordNonMatchCount: newRecordNonMatchCount, matchErrors: recordMatchErrors});\n }\n\n function candidateNotInMatches(matches, candidate) {\n debug(`Checking that record ${candidate.id} is not already included in ${matches.length} matches/nonMatches`);\n const newCandidateId = candidate.id;\n debugData(`newCandidateId: ${newCandidateId}`);\n const result = matches.find(({candidate}) => candidate.id === newCandidateId);\n debugData(`Result: ${result}`);\n if (result) {\n debug(`${candidate.id} was already handled.`);\n return false;\n }\n debug(`${candidate.id} not found in matches/nonMatches`);\n return true;\n }\n }\n\n function maxMatchesFound({matches, maxMatches}) {\n if (maxMatches && matches.length >= maxMatches) {\n debug(`Stopping recordSet iteration: maxMatches (${maxMatches}) for matcher job found.`);\n return true;\n }\n }\n }\n};\n"],"mappings":";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SAAS,CAACI,EAAE;QACnCnF,SAAS,CAAE,mBAAkB2G,cAAe,EAAC,CAAC;QAC9C,MAAMnD,MAAM,GAAG1C,OAAO,CAAC8F,IAAI,CAAC,CAAC;UAAC7B;QAAS,CAAC,KAAKA,SAAS,CAACI,EAAE,KAAKwB,cAAc,CAAC;QAC7E3G,SAAS,CAAE,WAAUwD,MAAO,EAAC,CAAC;QAC9B,IAAIA,MAAM,EAAE;UACV1D,KAAK,CAAE,GAAEiF,SAAS,CAACI,EAAG,uBAAsB,CAAC;UAC7C,OAAO,KAAK;QACd;QACArF,KAAK,CAAE,GAAEiF,SAAS,CAACI,EAAG,kCAAiC,CAAC;QACxD,OAAO,IAAI;MACb;IACF;IAEA,SAASvC,eAAeA,CAAC;MAAC9B,OAAO;MAAEtB;IAAU,CAAC,EAAE;MAC9C,IAAIA,UAAU,IAAIsB,OAAO,CAACU,MAAM,IAAIhC,UAAU,EAAE;QAC9CM,KAAK,CAAE,6CAA4CN,UAAW,0BAAyB,CAAC;QACxF,OAAO,IAAI;MACb;IACF;EACF;AACF,CAAC;AAAA9B,OAAA,CAAAS,OAAA,GAAAgB,QAAA"}
|
package/package.json
CHANGED
|
@@ -0,0 +1,123 @@
|
|
|
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) 2023 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 createDebugLogger from 'debug';
|
|
30
|
+
import createClient, {SruSearchError} from '@natlibfi/sru-client';
|
|
31
|
+
|
|
32
|
+
export class CandidateSearchError extends Error {}
|
|
33
|
+
|
|
34
|
+
export default async function ({url, queryList, queryListType, maxCandidates = 50}) {
|
|
35
|
+
|
|
36
|
+
const debug = createDebugLogger('@natlibfi/melinda-record-matching:candidate-search:choose-queries');
|
|
37
|
+
const debugData = debug.extend('data');
|
|
38
|
+
const debugDev = debug.extend('dev');
|
|
39
|
+
|
|
40
|
+
debugData(`Url: ${url}`);
|
|
41
|
+
debugData(`QueryList: ${queryList}`);
|
|
42
|
+
debugData(`queryListType: ${queryListType}`);
|
|
43
|
+
|
|
44
|
+
const client = createClient({
|
|
45
|
+
url,
|
|
46
|
+
maxRecordsPerRequest: 0,
|
|
47
|
+
version: '2.0',
|
|
48
|
+
retrieveAll: false
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
debugDev(`QueryList (type: ${queryListType}) ${JSON.stringify(queryList)}`);
|
|
52
|
+
try {
|
|
53
|
+
const {queriesWithTotals} = await getQueryTotals({queryList, queryOffset: 0, queriesWithTotals: []});
|
|
54
|
+
debugDev(`QueryResult: ${JSON.stringify(queriesWithTotals)}`);
|
|
55
|
+
const filteredQueryResult = filterQueryResult({queriesWithTotals, maxCandidates});
|
|
56
|
+
debugDev(`filteredQueryResult: ${JSON.stringify(filteredQueryResult)}`);
|
|
57
|
+
return filteredQueryResult;
|
|
58
|
+
} catch (err) {
|
|
59
|
+
throw new CandidateSearchError(err);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function getQueryTotals({queryList, queryOffset = 0, queriesWithTotals = []}) {
|
|
63
|
+
|
|
64
|
+
const query = queryList[queryOffset];
|
|
65
|
+
debug(`Running query ${JSON.stringify(query)} (${queryOffset}) for total`);
|
|
66
|
+
|
|
67
|
+
if (query) {
|
|
68
|
+
const {total} = await retrieveTotal();
|
|
69
|
+
|
|
70
|
+
const newQueriesWithTotals = [...queriesWithTotals, {query, total}];
|
|
71
|
+
debug(`Query ${queryOffset} ${query} done.`);
|
|
72
|
+
debug(`There are (${queryList.length - (queryOffset + 1)} queries left)`);
|
|
73
|
+
return getQueryTotals({queryList, queryOffset: queryOffset + 1, queriesWithTotals: newQueriesWithTotals});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
debug(`All ${queryList.length} queries done, there's no query for ${queryOffset}`);
|
|
77
|
+
return {queriesWithTotals};
|
|
78
|
+
|
|
79
|
+
function retrieveTotal() {
|
|
80
|
+
return new Promise((resolve, reject) => {
|
|
81
|
+
// eslint-disable-next-line functional/no-let
|
|
82
|
+
let totalRecords = 0;
|
|
83
|
+
|
|
84
|
+
debug(`Searching total amount of candidates for query: ${query}`);
|
|
85
|
+
|
|
86
|
+
client.searchRetrieve(query)
|
|
87
|
+
.on('error', err => {
|
|
88
|
+
// eslint-disable-next-line functional/no-conditional-statements
|
|
89
|
+
if (err instanceof SruSearchError) {
|
|
90
|
+
debug(`SRU SruSearchError for query: ${query}: ${err}`);
|
|
91
|
+
reject(new CandidateSearchError(`SRU SruSearchError for query: ${query}: ${err}`));
|
|
92
|
+
}
|
|
93
|
+
debug(`SRU error for query: ${query}: ${err}`);
|
|
94
|
+
reject(new CandidateSearchError(`SRU error for query: ${query}: ${err}`));
|
|
95
|
+
})
|
|
96
|
+
.on('total', total => {
|
|
97
|
+
debug(`Got total: ${total}`);
|
|
98
|
+
totalRecords += total;
|
|
99
|
+
})
|
|
100
|
+
.on('end', () => {
|
|
101
|
+
try {
|
|
102
|
+
resolve({total: totalRecords});
|
|
103
|
+
} catch (err) {
|
|
104
|
+
debug(`Error caught on END`);
|
|
105
|
+
reject(err);
|
|
106
|
+
}
|
|
107
|
+
})
|
|
108
|
+
.on('record', () => {
|
|
109
|
+
debugDev(`RECORD: We should no get records here`);
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function filterQueryResult({queriesWithTotals, maxCandidates}) {
|
|
115
|
+
debug(`Filtering queries (${queriesWithTotals.length}), maxCandidates: ${maxCandidates}`);
|
|
116
|
+
debugData(`${JSON.stringify(queriesWithTotals)}`);
|
|
117
|
+
// Drop queries where total result is 0 or greater than given maxCandidates
|
|
118
|
+
const filteredQueryResult = queriesWithTotals.filter((queryWithTotal) => queryWithTotal.total !== 0 && queryWithTotal.total < maxCandidates);
|
|
119
|
+
debugData(`${JSON.stringify(filteredQueryResult)}`);
|
|
120
|
+
return filteredQueryResult;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
}
|