# Reusable SearchQuery

Source: https://docs.rushdb.com/learn/tutorials/search-and-queries/reusable-search-query/

RushDB uses one core query object shape across multiple APIs.

You can reuse the same query logic across five perspectives on data:

- Records
- Properties
- Labels
- Relationships
- Values

Once you learn SearchQuery once, you can apply it almost everywhere.

## Canonical SearchQuery shape

**TypeScript**

```typescript
type SearchQuery = {
  labels?: string[]
  where?: Record<string, unknown>
  select?: Record<string, unknown>
  groupBy?: string[]
  orderBy?: 'asc' | 'desc' | Record<string, 'asc' | 'desc'>
  limit?: number
  skip?: number
}
```

**Python**

```python
# SearchQuery is a plain dict in Python
search_query = {
    "labels": ["..."],          # optional
    "where": {},                # optional
    "select": {},               # optional
    "groupBy": ["..."],         # optional
    "orderBy": "asc" | {"field": "asc"},  # optional
    "limit": 100,               # optional
    "skip": 0                   # optional
}
```

**Shell**

```bash
# SearchQuery is a JSON body passed to any search endpoint
{
  "labels": ["..."],
  "where": {},
  "select": {},
  "groupBy": ["..."],
  "orderBy": {"field": "asc"},
  "limit": 100,
  "skip": 0
}
```

Supported by:

- `records.find` / `/api/v1/records/search`
- `records.delete` / `/api/v1/records/delete`
- `relationships.find` / `/api/v1/relationships/search`
- `labels.find` / `/api/v1/labels/search`
- `properties.find` / `/api/v1/properties/search`

And paired with values exploration via `/api/v1/properties/:id/values`.

`where` is resource-local. For records, labels, properties, exports, and deletes it filters Records. For `relationships.find`, `where` filters relationship edges (`type` plus user-defined edge properties); use `source` and `target` for endpoint Record filters.

## Why it matters

- Reduced learning curve
- Reusable filtering logic across endpoints
- Predictable behavior for filtering, aggregation, and pagination
- Easier AI-assisted query generation because the shape stays stable

## One intent, five perspectives

SearchQuery's ultimate feature is intent reuse.

You can express one business question and view it from different perspectives:

- Records: return matching entities
- Properties: discover which fields participate in that slice
- Labels: discover which entity types match
- Relationships: inspect graph links within the same slice
- Values: enumerate canonical values for a chosen property in that slice

This means your app can move from listing to discovery to analytics without changing mental model.

## Where clause essentials

### Primitive and operator filters

**TypeScript**

```typescript
where: {
  status: { $in: ['active', 'pending'] },
  amount: { $gte: 1000, $lt: 5000 },
  name: { $contains: 'acme' },
  isArchived: { $ne: true }
}
```

**Python**

```python
"where": {
    "status": {"$in": ["active", "pending"]},
    "amount": {"$gte": 1000, "$lt": 5000},
    "name": {"$contains": "acme"},
    "isArchived": {"$ne": True}
}
```

**Shell**

```bash
"where": {
  "status": {"$in": ["active", "pending"]},
  "amount": {"$gte": 1000, "$lt": 5000},
  "name": {"$contains": "acme"},
  "isArchived": {"$ne": true}
}
```

### Logical composition

**TypeScript**

```typescript
where: {
  $or: [
    { status: 'active' },
    {
      $and: [{ status: 'pending' }, { priority: { $gte: 8 } }]
    }
  ]
}
```

**Python**

```python
"where": {
    "$or": [
        {"status": "active"},
        {
            "$and": [
                {"status": "pending"},
                {"priority": {"$gte": 8}}
            ]
        }
    ]
}
```

**Shell**

```bash
"where": {
  "$or": [
    {"status": "active"},
    {
      "$and": [
        {"status": "pending"},
        {"priority": {"$gte": 8}}
      ]
    }
  ]
}
```

### Relationship traversal

In SearchQuery, relationship traversal uses label keys directly.

**TypeScript**

```typescript
where: {
  DEPARTMENT: {
    $alias: '$department',
    name: 'Engineering',
    PROJECT: {
      $alias: '$project',
      EMPLOYEE: {
        $alias: '$employee',
        role: { $in: ['Developer', 'Lead'] }
      }
    }
  }
}
```

**Python**

```python
"where": {
    "DEPARTMENT": {
        "$alias": "$department",
        "name": "Engineering",
        "PROJECT": {
            "$alias": "$project",
            "EMPLOYEE": {
                "$alias": "$employee",
                "role": {"$in": ["Developer", "Lead"]}
            }
        }
    }
}
```

**Shell**

```bash
"where": {
  "DEPARTMENT": {
    "$alias": "$department",
    "name": "Engineering",
    "PROJECT": {
      "$alias": "$project",
      "EMPLOYEE": {
        "$alias": "$employee",
        "role": {"$in": ["Developer", "Lead"]}
      }
    }
  }
}
```

Important:

- Use the label key itself (`DEPARTMENT`, `PROJECT`, `EMPLOYEE`) to traverse
- Use `$alias` to reference traversed nodes in `select` and `groupBy`
- Do not use unsupported traversal fields such as `$label`, `$as`, `$through`, `$of`

### Date range rule

For range operators on datetimes, use component objects.

**TypeScript**

```typescript
where: {
  createdAt: {
    $gte: { $year: 2025, $month: 1, $day: 1 },
    $lt: { $year: 2026, $month: 1, $day: 1 }
  }
}
```

**Python**

```python
"where": {
    "createdAt": {
        "$gte": {"$year": 2025, "$month": 1, "$day": 1},
        "$lt": {"$year": 2026, "$month": 1, "$day": 1}
    }
}
```

**Shell**

```bash
"where": {
  "createdAt": {
    "$gte": {"$year": 2025, "$month": 1, "$day": 1},
    "$lt": {"$year": 2026, "$month": 1, "$day": 1}
  }
}
```

## GroupBy

SearchQuery supports grouped analytics using the `select` and `groupBy` clauses.

### Per-record flat metrics

**TypeScript**

```typescript
const rows = await db.records.find({
  labels: ['PROJECT'],
  where: {
    EMPLOYEE: { $alias: '$employee' }
  },
  select: {
    projectName: '$record.name',
    headcount: { $count: '$employee' },
    totalSalary: { $sum: '$employee.salary' }
  },
  limit: 100
})
```

**Python**

```python
rows = db.records.find({
    "labels": ["PROJECT"],
    "where": {
        "EMPLOYEE": {"$alias": "$employee"}
    },
    "select": {
        "projectName": "$record.name",
        "headcount": {"$count": "$employee"},
        "totalSalary": {"$sum": "$employee.salary"}
    },
    "limit": 100
})
```

**Shell**

```bash
curl -X POST "https://api.rushdb.com/api/v1/records/search" \
  -H "Authorization: Bearer $RUSHDB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "labels": ["PROJECT"],
    "where": {"EMPLOYEE": {"$alias": "$employee"}},
    "select": {
      "projectName": "$record.name",
      "headcount": {"$count": "$employee"},
      "totalSalary": {"$sum": "$employee.salary"}
    },
    "limit": 100
  }'
```

### Dimensional groupBy

**TypeScript**

```typescript
const byStatus = await db.records.find({
  labels: ['ORDER'],
  select: {
    count: { $count: '*' },
    revenue: { $sum: '$record.total' }
  },
  groupBy: ['$record.status'],
  orderBy: { revenue: 'desc' }
})
```

**Python**

```python
by_status = db.records.find({
    "labels": ["ORDER"],
    "select": {
        "count":   {"$count": "*"},
        "revenue": {"$sum": "$record.total"}
    },
    "groupBy": ["$record.status"],
    "orderBy": {"revenue": "desc"}
})
```

**Shell**

```bash
curl -X POST "https://api.rushdb.com/api/v1/records/search" \
  -H "Authorization: Bearer $RUSHDB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "labels": ["ORDER"],
    "select": {
      "count":   {"$count": "*"},
      "revenue": {"$sum": "$record.total"}
    },
    "groupBy": ["$record.status"],
    "orderBy": {"revenue": "desc"}
  }'
```

### Self-group (single-row KPI)

**TypeScript**

```typescript
const totals = await db.records.find({
  labels: ['ORDER'],
  select: {
    totalRevenue: { $sum: '$record.total' }
  },
  groupBy: ['totalRevenue'],
  orderBy: { totalRevenue: 'asc' }
})
```

**Python**

```python
totals = db.records.find({
    "labels": ["ORDER"],
    "select": {
        "totalRevenue": {"$sum": "$record.total"}
    },
    "groupBy": ["totalRevenue"],
    "orderBy": {"totalRevenue": "asc"}
})
```

**Shell**

```bash
curl -X POST "https://api.rushdb.com/api/v1/records/search" \
  -H "Authorization: Bearer $RUSHDB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "labels": ["ORDER"],
    "select": {
      "totalRevenue": {"$sum": "$record.total"}
    },
    "groupBy": ["totalRevenue"],
    "orderBy": {"totalRevenue": "asc"}
  }'
```

## Critical limit rules

- Do not use `limit` in self-group KPI queries
- Do not use `limit` in dimensional groupBy unless intentionally asking for top N groups
- `limit` is valid for listing/browsing and per-record flat aggregation
- For self-group KPI queries, include `orderBy` on the select key to force full-scan aggregation behavior

## Reusable patterns across APIs

### 1. Search records

**TypeScript**
```typescript
const products = await db.records.find({
  labels: ['PRODUCT'],
  where: {
    active: true,
    price: { $gte: 10, $lte: 50 },
    tags: { $in: ['featured'] }
  },
  orderBy: { price: 'asc' },
  limit: 20,
  skip: 0
})
```
**Python**
```python
result = db.records.find({
  "labels": ["PRODUCT"],
  "where": {
    "active": True,
    "price": {"$gte": 10, "$lte": 50},
    "tags": {"$in": ["featured"]}
  },
  "orderBy": {"price": "asc"},
  "limit": 20,
  "skip": 0
})
products = result.data
```
**Shell**
```bash
curl -X POST "https://api.rushdb.com/api/v1/records/search" \
  -H "Authorization: Bearer $RUSHDB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "labels": ["PRODUCT"],
    "where": {
      "active": true,
      "price": {
        "$gte": 10,
        "$lte": 50
      },
      "tags": { "$in": ["featured"] }
    },
    "orderBy": {"price": "asc"},
    "limit": 20,
    "skip": 0
  }'
```

### 2. Delete records with the same where logic

**TypeScript**
```typescript
await db.records.delete({
  labels: ['PRODUCT'],
  where: {
    discontinued: true,
    inventory: 0
  }
})
```
**Python**
```python
db.records.delete({
  "labels": ["PRODUCT"],
  "where": {
    "discontinued": True,
    "inventory": 0
  }
})
```
**Shell**
```bash
curl -X PUT "https://api.rushdb.com/api/v1/records/delete" \
  -H "Authorization: Bearer $RUSHDB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "labels": ["PRODUCT"],
    "where": {
      "discontinued": true,
      "inventory": 0
    }
  }'
```

### 3. Search relationships

**TypeScript**
```typescript
const createdRelationships = await db.relationships.find({
  source: { labels: ['USER'], where: { group: 'admin' } },
  where: {
    type: 'CREATED',
    weight: { $gte: 0.5 }
  },
  limit: 50
})
```
**Python**
```python
created_relationships = db.relationships.find({
  "source": {"labels": ["USER"], "where": {"group": "admin"}},
  "where": {
    "type": "CREATED",
    "weight": {"$gte": 0.5}
  },
  "limit": 50
})
```
**Shell**
```bash
# Find all CREATED relationships by users in the admin group
curl -X POST "https://api.rushdb.com/api/v1/relationships/search" \
  -H "Authorization: Bearer $RUSHDB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "source": { "labels": ["USER"], "where": { "group": "admin" } },
    "where": {
      "type": "CREATED",
      "weight": { "$gte": 0.5 }
    },
    "limit": 50
  }'
```

### 4. Find labels by data constraints

**TypeScript**
```typescript
const labels = await db.labels.find({
  where: {
    region: { $in: ['US', 'CA', 'MX'] }
  }
})
```
**Python**
```python
labels = db.labels.find({
  "where": {
    "region": {"$in": ["US", "CA", "MX"]}
  }
})
```
**Shell**
```bash
# Find all labels used on records in North America region
curl -X POST "https://api.rushdb.com/api/v1/labels/search" \
  -H "Authorization: Bearer $RUSHDB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "where": {
      "region": {"$in": ["US", "CA", "MX"]}
    }
  }'
```

### 5. Discover properties for a label

**TypeScript**
```typescript
const productProps = await db.properties.find({
  labels: ['PRODUCT'],
  where: {
    type: 'number'
  }
})
```
**Python**
```python
product_props = db.properties.find({
  "labels": ["PRODUCT"],
  "where": {
    "type": "number"
  }
})
```
**Shell**
```bash
curl -X POST "https://api.rushdb.com/api/v1/properties/search" \
  -H "Authorization: Bearer $RUSHDB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "labels": ["PRODUCT"],
    "where": {
      "type": "number"
    }
  }'
```

### 6. Explore values for a selected property

Use values as the final perspective when you need canonical filter options for UI facets, prompts, and dynamic query builders.

Typical flow:

1. Use `properties.find` to locate a property and get its id
2. Call `/api/v1/properties/:id/values` for value discovery in the same data context
3. Feed returned canonical values back into your next SearchQuery (`$in`, `$nin`, exact match)

## Common pitfalls to avoid

- Using `limit` on KPI/self-group queries
- Using traversal keys like `$label` instead of real label keys (`EMPLOYEE`, `PROJECT`)
- Treating `groupBy` self-group keys as property paths instead of `select` key names
- Using plain date strings with `$gt`/`$gte`/`$lt`/`$lte` instead of datetime component objects

## API reference links

| Endpoint                        | Docs                                                               |
| ------------------------------- | ------------------------------------------------------------------ |
| `/api/v1/records/search`        | [Records API](../../reference/rest-api/records/get-records.md)       |
| `/api/v1/records/delete`        | [Delete Records](../../reference/rest-api/records/delete-records.md) |
| `/api/v1/relationships/search`  | [Relationships API](../../reference/rest-api/relationships.md)       |
| `/api/v1/labels/search`         | [Labels API](../../reference/rest-api/labels.md)                     |
| `/api/v1/properties/search`     | [Properties API](../../reference/rest-api/properties.md)             |
| `/api/v1/properties/:id/values` | [Properties API](../../reference/rest-api/properties.md)             |

## Next step

If you want advanced examples (nested collect, multi-hop traversal, time buckets, KPI patterns), continue with the deep-dive tutorial:

[SearchQuery Deep Dive: Advanced Patterns](./searchquery-advanced-patterns.mdx)
