-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsearch.js
More file actions
390 lines (370 loc) · 15.1 KB
/
search.js
File metadata and controls
390 lines (370 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#!/usr/bin/env node
/**
* Basic CRUD operations for RERUM v1
* @author Claude Sonnet 4, cubap, thehabes
*/
import { newID, isValidID, db } from '../database/index.js'
import utils from '../utils.js'
import { _contextid, idNegotiation, generateSlugId, ObjectID, createExpressError, getAgentClaim, parseDocumentID } from './utils.js'
/**
* Merges and deduplicates results from multiple MongoDB Atlas Search index queries.
*
* This function combines search results from both the IIIF Presentation API 3.0 index
* (presi3AnnotationText) and the IIIF Presentation API 2.1 index (presi2AnnotationText).
*
* @param {Array<Object>} results1 - Results from the first search index (typically IIIF 3.0)
* @param {Array<Object>} results2 - Results from the second search index (typically IIIF 2.1)
* @returns {Array<Object>} Merged array of unique results sorted by search score (descending)
*
* @description
* Process:
* 1. Combines both result arrays
* 2. Removes duplicates based on MongoDB _id (keeps first occurrence)
* 3. Sorts by search score in descending order (highest relevance first)
*
* The function handles different _id formats:
* - ObjectId objects with $oid property
* - String-based _id values
*
*/
function mergeSearchResults(results1, results2) {
const seen = new Set()
const merged = []
for (const result of [...results1, ...results2]) {
const id = result._id?.$oid || result._id?.toString()
if (!seen.has(id)) {
seen.add(id)
merged.push(result)
}
}
// Sort by score descending
return merged.sort((a, b) => (b.score || 0) - (a.score || 0))
}
/**
* Builds parallel MongoDB Atlas Search aggregation pipelines for both IIIF 3.0 and 2.1 indexes.
*
* This function creates two separate search queries that will be executed in parallel:
* - One for IIIF Presentation API 3.0 resources (presi3AnnotationText index)
* - One for IIIF Presentation API 2.1 resources (presi2AnnotationText index)
*
* @param {string} searchText - The text query to search for
* @param {Object} operator - Search operator configuration
* @param {string} operator.type - Type of search operator: "text", "wildcard", "phrase", etc.
* @param {Object} operator.options - Additional options for the search operator (e.g., fuzzy options)
* @param {number} limit - Maximum number of results to return per index
* @param {number} skip - Number of results to skip for pagination
* @returns {Array<Array>} Two-element array containing [presi3Pipeline, presi2Pipeline]
*
* @description
* IIIF 3.0 Query Structure (presi3AnnotationText index):
* - Searches direct text fields: body.value, bodyValue
* - Searches embedded items: items.annotations.items.body.value
* - Searches annotation items: annotations.items.body.value
* - Uses compound query with "should" clauses (any match qualifies)
*
* IIIF 2.1 Query Structure (presi2AnnotationText index):
* - Searches Open Annotation fields: resource.chars, resource.cnt:chars
* - Searches AnnotationList resources: resources[].resource.chars
* - Searches Canvas otherContent: otherContent[].resources[].resource.chars
* - Searches Manifest sequences: sequences[].canvases[].otherContent[].resources[].resource.chars
* - Uses nested embeddedDocument operators for multi-level array traversal
*
* Both queries use:
* - $search stage with the specified operator type (text, wildcard, phrase, etc.)
* - $addFields to include searchScore metadata
* - $limit to cap results (limit + skip to allow for pagination)
*/
function buildDualIndexQueries(searchText, operator, limit, skip) {
const presi3Query = {
index: "presi3AnnotationText",
compound: {
should: [
{
[operator.type]: {
query: searchText,
path: ["body.value", "bodyValue"],
...operator.options
}
},
{
embeddedDocument: {
path: "items.annotations.items",
operator: {
[operator.type]: {
query: searchText,
path: ["items.annotations.items.body.value", "items.annotations.items.bodyValue"],
...operator.options
}
}
}
},
{
embeddedDocument: {
path: "annotations",
operator: {
[operator.type]: {
query: searchText,
path: ["annotations.items.body.value", "annotations.items.bodyValue"],
...operator.options
}
}
}
},
{
embeddedDocument: {
path: "annotations.items",
operator: {
[operator.type]: {
query: searchText,
path: ["annotations.items.body.value", "annotations.items.bodyValue"],
...operator.options
}
}
}
},
{
embeddedDocument: {
path: "items",
operator: {
[operator.type]: {
query: searchText,
path: [
"items.body.value",
"items.bodyValue",
"items.annotations.items.body.value",
"items.annotations.items.bodyValue"
],
...operator.options
}
}
}
}
],
minimumShouldMatch: 1
}
}
const presi2Query = {
index: "presi2AnnotationText",
compound: {
should: [
{
[operator.type]: {
query: searchText,
path: ["resource.chars", "resource.cnt:chars"],
...operator.options
}
},
{
embeddedDocument: {
path: "resources",
operator: {
[operator.type]: {
query: searchText,
path: ["resources.resource.chars", "resources.resource.cnt:chars"],
...operator.options
}
}
}
},
{
embeddedDocument: {
path: "otherContent.resources",
operator: {
[operator.type]: {
query: searchText,
path: ["otherContent.resources.resource.chars", "otherContent.resources.resource.cnt:chars"],
...operator.options
}
}
}
},
{
embeddedDocument: {
path: "sequences.canvases.otherContent.resources",
operator: {
[operator.type]: {
query: searchText,
path: [
"sequences.canvases.otherContent.resources.resource.chars",
"sequences.canvases.otherContent.resources.resource.cnt:chars"
],
...operator.options
}
}
}
}
],
minimumShouldMatch: 1
}
}
return [
[
{ $search: presi3Query },
{ $addFields: { "__rerum.score": { $meta: "searchScore" } } },
{ $limit: limit + skip }
],
[
{ $search: presi2Query },
{ $addFields: { "__rerum.score": { $meta: "searchScore" } } },
{ $limit: limit + skip }
]
]
}
/**
* Standard text search endpoint - searches for exact word matches across both IIIF 3.0 and 2.1 resources.
*
* @route POST /search
* @param {Object} req.body - Request body containing search text
* @param {string} req.body.searchText - The text to search for (can also be a plain string body)
* @param {number} [req.query.limit=100] - Maximum number of results to return
* @param {number} [req.query.skip=0] - Number of results to skip for pagination
* @returns {Array<Object>} JSON array of matching annotation objects sorted by relevance score
*
* @description
* Performs a standard MongoDB Atlas Search text query that:
* - Tokenizes the search text into words
* - Searches for exact word matches (case-insensitive)
* - Applies standard linguistic analysis (stemming, stop words, etc.)
* - Searches across both IIIF Presentation API 3.0 and 2.1 indexes in parallel
* - Returns results sorted by relevance score (highest first)
*
* Search Behavior:
* - "Bryan Haberberger" → finds documents containing both "Bryan" AND "Haberberger"
* - Searches are case-insensitive
* - Standard analyzer removes common stop words
* - Partial word matches are NOT supported (use wildcardSearch for that)
*
* IIIF 3.0 Fields Searched:
* - body.value, bodyValue (direct annotation text)
* - items.*.body.value (nested structures)
* - annotations.*.body.value (canvas annotations)
*
* IIIF 2.1 Fields Searched:
* - resource.chars, resource.cnt:chars (direct annotation text)
* - resources[].resource.chars (AnnotationList)
* - otherContent[].resources[].resource.chars (Canvas)
* - sequences[].canvases[].otherContent[].resources[].resource.chars (Manifest)
*
* @example
* POST /search
* Body: {"searchText": "Hello World"}
* Returns: All annotations containing "Hello" and "World"
*
*/
const searchAsWords = async function (req, res, next) {
res.set("Content-Type", "application/json; charset=utf-8")
let searchText = req.body?.searchText ?? req.body
if (!searchText) {
let err = {
message: "You did not provide text to search for in the search request.",
status: 400
}
next(createExpressError(err))
return
}
const limit = parseInt(req.query.limit ?? 100)
const skip = parseInt(req.query.skip ?? 0)
const [queryPresi3, queryPresi2] = buildDualIndexQueries(searchText, { type: "text", options: {} }, limit, skip)
try {
const [resultsPresi3, resultsPresi2] = await Promise.all([
db.aggregate(queryPresi3).toArray().catch((err) => { console.error("Presi3 error:", err.message); return [] }),
db.aggregate(queryPresi2).toArray().catch((err) => { console.error("Presi2 error:", err.message); return [] })
])
const merged = mergeSearchResults(resultsPresi3, resultsPresi2)
const results = merged.slice(skip, skip + limit)
res.set(utils.configureLDHeadersFor(results))
res.json(results)
} catch (error) {
console.error(error)
next(createExpressError(error))
}
}
/**
* Phrase search endpoint - searches for multi-word phrases with words in proximity.
*
* @route POST /phraseSearch
* @param {Object} req.body - Request body containing search phrase
* @param {string} req.body.searchText - The phrase to search for (can also be a plain string body)
* @param {number} [req.query.limit=100] - Maximum number of results to return
* @param {number} [req.query.skip=0] - Number of results to skip for pagination
* @returns {Array<Object>} JSON array of matching annotation objects sorted by relevance score
*
* @description
* Performs a phrase search that finds documents where search terms appear near each other:
* - Searches for terms in sequence or close proximity
* - Allows up to 2 intervening words between search terms (slop: 2)
* - More precise than standard text search for multi-word queries
* - Searches across both IIIF Presentation API 3.0 and 2.1 indexes in parallel
*
* Phrase Options:
* - slop: 2 (allows up to 2 words between search terms)
*
* Phrase Matching Examples (with slop: 2):
* - "Bryan Haberberger" → matches:
* ✓ "Bryan Haberberger"
* ✓ "Bryan the Haberberger"
* ✓ "Bryan A. Haberberger"
* ✗ "Bryan loves to eat hamburgers with Haberberger" (too many words between)
*
* - "manuscript illumination" → matches:
* ✓ "manuscript illumination"
* ✓ "manuscript and illumination"
* ✓ "illumination of manuscript" (reversed order with slop)
* ✓ "illuminated manuscript"
*
* Use Cases:
* - Finding exact or near-exact phrases
* - Searching for names or titles
* - Looking for specific multi-word concepts
* - More precise than standard search, more flexible than exact match
*
* Comparison with Other Search Types:
* - Standard search: Finds "Bryan" AND "Haberberger" anywhere in document
* - Phrase search: Finds "Bryan" near "Haberberger" (within 2 words)
* - Exact match: Would require "Bryan Haberberger" with no intervening words
*
* Performance:
* - Generally faster than wildcard search
* - Slower than standard text search due to proximity calculations
* - Good balance of precision and recall
*
* @example
* POST /phraseSearch
* Body: "medieval manuscript"
* Returns: Annotations with "medieval" and "manuscript" in proximity
*/
const searchAsPhrase = async function (req, res, next) {
res.set("Content-Type", "application/json; charset=utf-8")
let searchText = req.body?.searchText ?? req.body
if (!searchText) {
let err = {
message: "You did not provide text to search for in the search request.",
status: 400
}
next(createExpressError(err))
return
}
const limit = parseInt(req.query.limit ?? 100)
const skip = parseInt(req.query.skip ?? 0)
const phraseOptions = {
slop: 2
}
const [queryPresi3, queryPresi2] = buildDualIndexQueries(searchText, { type: "phrase", options: phraseOptions }, limit, skip)
try {
const [resultsPresi3, resultsPresi2] = await Promise.all([
db.aggregate(queryPresi3).toArray().catch(() => []),
db.aggregate(queryPresi2).toArray().catch(() => [])
])
const merged = mergeSearchResults(resultsPresi3, resultsPresi2)
const results = merged.slice(skip, skip + limit)
res.set(utils.configureLDHeadersFor(results))
res.json(results)
} catch (error) {
console.error(error)
next(createExpressError(error))
}
}
export {
searchAsWords,
searchAsPhrase
}