Skip to content

Commit 7a628e5

Browse files
committed
Optimize batched Anki duplicate searches
1 parent 649cfb0 commit 7a628e5

1 file changed

Lines changed: 22 additions & 2 deletions

File tree

ext/js/comm/anki-connect.js

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,7 @@ export class AnkiConnect {
309309
if (!this._enabled) { return []; }
310310
await this._checkVersion();
311311

312-
const actions = [];
312+
const queries = [];
313313
const actionsTargetsList = [];
314314
/** @type {Map<string, import('anki').NoteId[][]>} */
315315
const actionsTargetsMap = new Map();
@@ -323,14 +323,34 @@ export class AnkiConnect {
323323
actionsTargets = [];
324324
actionsTargetsList.push(actionsTargets);
325325
actionsTargetsMap.set(query, actionsTargets);
326-
actions.push({action: 'findNotes', params: {query}});
326+
queries.push(query);
327327
}
328328
/** @type {import('anki').NoteId[]} */
329329
const noteIds = [];
330330
allNoteIds.push(noteIds);
331331
actionsTargets.push(noteIds);
332332
}
333333

334+
if (queries.length === 0) { return allNoteIds; }
335+
336+
let actions;
337+
const hasEmptyQuery = queries.some((query) => query.length === 0);
338+
if (queries.length === 1 || hasEmptyQuery) {
339+
actions = queries.map((query) => ({action: 'findNotes', params: {query}}));
340+
} else {
341+
// Find the union once, then constrain each original query to the candidate notes.
342+
const unionQuery = queries.map((query) => `(${query})`).join(' or ');
343+
const unionResult = await this._invoke('findNotes', {query: unionQuery});
344+
const candidateNoteIds = /** @type {number[]} */ (this._normalizeArray(unionResult, -1, 'number'));
345+
if (candidateNoteIds.length === 0) { return allNoteIds; }
346+
347+
const candidateFilter = `nid:${candidateNoteIds.join(',')}`;
348+
actions = queries.map((query) => ({
349+
action: 'findNotes',
350+
params: {query: `${candidateFilter} (${query})`},
351+
}));
352+
}
353+
334354
const result = await this._invokeMulti(actions);
335355
for (let i = 0, ii = Math.min(result.length, actionsTargetsList.length); i < ii; ++i) {
336356
const noteIds = /** @type {number[]} */ (this._normalizeArray(result[i], -1, 'number'));

0 commit comments

Comments
 (0)