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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
|
---
title: "Query Rewriting"
description: "Improve search accuracy with automatic query expansion and rewriting"
---

Query rewriting automatically generates multiple variations of your search query to improve result coverage and accuracy. Supermemory creates several rewrites, searches through all of them, then merges and deduplicates the results.
## How Query Rewriting Works
When you enable `rewriteQuery: true`, Supermemory:
1. **Analyzes your original query** for intent and key concepts
2. **Generates multiple rewrites** with different phrasings and synonyms
3. **Executes searches** for both original and rewritten queries in parallel
4. **Merges and deduplicates** results from all queries
5. **Returns unified results** ranked by relevance
This process adds ~400ms latency but significantly improves result quality, especially for:
- **Natural language questions** ("How do neural networks learn?")
- **Ambiguous terms** that could have multiple meanings
- **Complex queries** with multiple concepts
- **Domain-specific terminology** that might have synonyms
## Basic Query Rewriting
<Tabs>
<Tab title="TypeScript">
```typescript
import Supermemory from 'supermemory';
const client = new Supermemory({
apiKey: process.env.SUPERMEMORY_API_KEY!
});
// Without query rewriting
const basicResults = await client.search.documents({
q: "How do transformers work in AI?",
rewriteQuery: false,
limit: 5
});
// With query rewriting - generates multiple query variations
const rewrittenResults = await client.search.documents({
q: "How do transformers work in AI?",
rewriteQuery: true,
limit: 5
});
console.log(`Basic search: ${basicResults.total} results`);
console.log(`Rewritten search: ${rewrittenResults.total} results`);
```
</Tab>
<Tab title="Python">
```python
from supermemory import Supermemory
import os
client = Supermemory(api_key=os.environ.get("SUPERMEMORY_API_KEY"))
# Without query rewriting
basic_results = client.search.documents(
q="How do transformers work in AI?",
rewrite_query=False,
limit=5
)
# With query rewriting - generates multiple query variations
rewritten_results = client.search.documents(
q="How do transformers work in AI?",
rewrite_query=True,
limit=5
)
print(f"Basic search: {basic_results.total} results")
print(f"Rewritten search: {rewritten_results.total} results")
```
</Tab>
<Tab title="cURL">
```bash
# Without query rewriting
echo "Basic search:"
curl -X POST "https://api.supermemory.ai/v3/search" \
-H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"q": "How do transformers work in AI?",
"rewriteQuery": false,
"limit": 5
}' | jq '.total'
# With query rewriting
echo "Rewritten search:"
curl -X POST "https://api.supermemory.ai/v3/search" \
-H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"q": "How do transformers work in AI?",
"rewriteQuery": true,
"limit": 5
}' | jq '.total'
```
</Tab>
</Tabs>
**Sample Output Comparison:**
```json
// Without rewriting: 3 results
{
"results": [...],
"total": 3,
"timing": 120
}
// With rewriting: 8 results (found more relevant content)
{
"results": [...],
"total": 8,
"timing": 520 // +400ms for query processing
}
```
## Natural Language Questions
Query rewriting excels at converting conversational questions into effective search queries:
<Tabs>
<Tab title="TypeScript">
```typescript
// Natural language question
const results = await client.search.documents({
q: "What are the best practices for training deep learning models?",
rewriteQuery: true,
limit: 10
});
// The system might generate rewrites like:
// - "deep learning model training best practices"
// - "neural network training optimization techniques"
// - "machine learning model training guidelines"
// - "deep learning training methodology"
```
</Tab>
<Tab title="Python">
```python
# Natural language question
results = client.search.documents(
q="What are the best practices for training deep learning models?",
rewrite_query=True,
limit=10
)
# The system might generate rewrites like:
# - "deep learning model training best practices"
# - "neural network training optimization techniques"
# - "machine learning model training guidelines"
# - "deep learning training methodology"
```
</Tab>
<Tab title="cURL">
```bash
curl -X POST "https://api.supermemory.ai/v3/search" \
-H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"q": "What are the best practices for training deep learning models?",
"rewriteQuery": true,
"limit": 10
}'
```
</Tab>
</Tabs>
**Sample Output:**
```json
{
"results": [
{
"documentId": "doc_123",
"title": "Deep Learning Training Guide",
"score": 0.92,
"chunks": [
{
"content": "Best practices for training deep neural networks include proper weight initialization, learning rate scheduling, and regularization techniques...",
"score": 0.89,
"isRelevant": true
}
]
},
{
"documentId": "doc_456",
"title": "Neural Network Optimization",
"score": 0.87,
"chunks": [
{
"content": "Effective training methodologies involve batch normalization, dropout, and gradient clipping to prevent overfitting...",
"score": 0.85,
"isRelevant": true
}
]
}
],
"total": 12,
"timing": 445
}
```
## Technical Term Expansion
Query rewriting helps find content using different technical terminologies:
<Tabs>
<Tab title="TypeScript">
```typescript
// Original query with specific terminology
const results = await client.search.documents({
q: "CNN architecture patterns",
rewriteQuery: true,
containerTags: ["research"],
limit: 8
});
// System expands to include:
// - "convolutional neural network architecture"
// - "CNN design patterns"
// - "convolutional network structures"
// - "CNN architectural components"
```
</Tab>
<Tab title="Python">
```python
# Original query with specific terminology
results = client.search.documents(
q="CNN architecture patterns",
rewrite_query=True,
container_tags=["research"],
limit=8
)
# System expands to include:
# - "convolutional neural network architecture"
# - "CNN design patterns"
# - "convolutional network structures"
# - "CNN architectural components"
```
</Tab>
<Tab title="cURL">
```bash
curl -X POST "https://api.supermemory.ai/v3/search" \
-H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"q": "CNN architecture patterns",
"rewriteQuery": true,
"containerTags": ["research"],
"limit": 8
}'
```
</Tab>
</Tabs>
**Sample Output:**
```json
{
"results": [
{
"documentId": "doc_789",
"title": "Convolutional Neural Network Architectures",
"score": 0.94,
"chunks": [
{
"content": "Modern CNN architectures like ResNet and DenseNet utilize skip connections to address the vanishing gradient problem...",
"score": 0.91,
"isRelevant": true
}
]
},
{
"documentId": "doc_101",
"title": "Deep Learning Design Patterns",
"score": 0.88,
"chunks": [
{
"content": "Convolutional layers followed by pooling operations form the fundamental building blocks of CNN architectures...",
"score": 0.86,
"isRelevant": true
}
]
}
],
"total": 15,
"timing": 478
}
```
## Memory Search with Query Rewriting
Query rewriting works with both document and memory search:
<Tabs>
<Tab title="TypeScript">
```typescript
// Memory search with query rewriting
const memoryResults = await client.search.memories({
q: "explain quantum entanglement simply",
rewriteQuery: true,
containerTag: "physics_notes",
limit: 5
});
// Generates variations like:
// - "quantum entanglement explanation"
// - "what is quantum entanglement"
// - "quantum entanglement basics"
// - "simple quantum entanglement description"
```
</Tab>
<Tab title="Python">
```python
# Memory search with query rewriting
memory_results = client.search.memories(
q="explain quantum entanglement simply",
rewrite_query=True,
container_tag="physics_notes",
limit=5
)
# Generates variations like:
# - "quantum entanglement explanation"
# - "what is quantum entanglement"
# - "quantum entanglement basics"
# - "simple quantum entanglement description"
```
</Tab>
<Tab title="cURL">
```bash
curl -X POST "https://api.supermemory.ai/v4/search" \
-H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"q": "explain quantum entanglement simply",
"rewriteQuery": true,
"containerTag": "physics_notes",
"limit": 5
}'
```
</Tab>
</Tabs>
**Sample Output:**
```json
{
"results": [
{
"id": "mem_456",
"memory": "Quantum entanglement is a phenomenon where two particles become connected in such a way that measuring one instantly affects the other, regardless of distance. Think of it like having two magical coins that always land on opposite sides.",
"similarity": 0.91,
"title": "Simple Quantum Entanglement Explanation",
"metadata": {
"topic": "quantum-physics",
"difficulty": "beginner"
}
},
{
"id": "mem_789",
"memory": "Einstein called quantum entanglement 'spooky action at a distance' because entangled particles seem to communicate instantaneously across vast distances, challenging our understanding of locality in physics.",
"similarity": 0.87,
"title": "Einstein's View on Entanglement"
}
],
"total": 7,
"timing": 412
}
```
## Complex Multi-Concept Queries
Query rewriting excels at handling queries with multiple concepts:
<Tabs>
<Tab title="TypeScript">
```typescript
const results = await client.search.documents({
q: "machine learning bias fairness algorithmic discrimination",
rewriteQuery: true,
filters: {
AND: [
{ key: "category", value: "ethics", negate: false }
]
},
limit: 10
});
// Breaks down into focused rewrites:
// - "machine learning bias detection"
// - "algorithmic fairness in AI"
// - "discrimination in machine learning algorithms"
// - "bias mitigation techniques ML"
```
</Tab>
<Tab title="Python">
```python
results = client.search.documents(
q="machine learning bias fairness algorithmic discrimination",
rewrite_query=True,
filters={
"AND": [
{"key": "category", "value": "ethics", "negate": False}
]
},
limit=10
)
# Breaks down into focused rewrites:
# - "machine learning bias detection"
# - "algorithmic fairness in AI"
# - "discrimination in machine learning algorithms"
# - "bias mitigation techniques ML"
```
</Tab>
<Tab title="cURL">
```bash
curl -X POST "https://api.supermemory.ai/v3/search" \
-H "Authorization: Bearer $SUPERMEMORY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"q": "machine learning bias fairness algorithmic discrimination",
"rewriteQuery": true,
"filters": {
"AND": [
{"key": "category", "value": "ethics", "negate": false}
]
},
"limit": 10
}'
```
</Tab>
</Tabs>
|