Untitled

mail@pastecode.io avatar
unknown
plain_text
25 days ago
2.1 kB
5
Indexable
Never
To meet your requirements for a fast SQL-based search across all levels of the `scanning_info` JSON field, we can use PostgreSQL's JSON operators and indexing. Here's a solution:

1. First, create a GIN index on the `scanning_info` field:

```sql
CREATE INDEX idx_run_scanning_info ON run USING GIN ((scanning_info) jsonb_path_ops);
```

2. Then, use the following SQL query to search for a given serial number:

```sql
SELECT id FROM run
WHERE scanning_info @> '{"sn": "SEARCH_SN"}'
   OR scanning_info @> '{"children": [{"sn": "SEARCH_SN"}]}'
   OR scanning_info::jsonb @@ '$.**.sn == "SEARCH_SN"'
```

Replace `SEARCH_SN` with the actual serial number you're searching for.

This query:
- Checks the top-level `sn`
- Checks the first level of children
- Uses JSON path expressions to search all nested levels

To implement this in Django:

1. Add the index in a migration:

```python
from django.contrib.postgres.indexes import GinIndex

class Migration(migrations.Migration):
    dependencies = [
        ('your_app', 'previous_migration'),
    ]

    operations = [
        GinIndex(fields=['scanning_info'], name='idx_run_scanning_info', opclass='jsonb_path_ops'),
    ]
```

2. Create a custom manager method:

```python
from django.db import models
from django.contrib.postgres.fields import JSONField

class RunManager(models.Manager):
    def search_by_sn(self, sn):
        return self.filter(
            models.Q(scanning_info__sn=sn) |
            models.Q(scanning_info__children__contains=[{'sn': sn}]) |
            models.Q(scanning_info__jsonfield__exact=models.F('scanning_info__jsonfield').text('$.**.sn == "%s"' % sn))
        )

class Run(models.Model):
    # ... existing fields ...
    
    objects = RunManager()
```

3. Use the custom manager in your API view:

```python
def search_runs(request):
    sn = request.GET.get('sn')
    runs = Run.objects.search_by_sn(sn).values_list('id', flat=True)
    return JsonResponse(list(runs), safe=False)
```

This solution provides a fast, SQL-based search across all levels of the JSON structure, utilizing PostgreSQL's JSON capabilities and appropriate indexing.
Leave a Comment