Skip to content

Commit

Permalink
docs(README): Field preprocessing/Related objects, fixes #2
Browse files Browse the repository at this point in the history
  • Loading branch information
PLNech committed Aug 21, 2017
1 parent 448f6b3 commit 0f70028
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ You can find the full reference on [Algolia's website](https://www.algolia.com/d

* [Custom `objectID`](#custom-objectid)
* [Custom index name](#custom-index-name)
* [Field Preprocessing and Related objects](#field-preprocessing-and-related-objects)
* [Index settings](#index-settings)
* [Restrict indexing to a subset of your data](#restrict-indexing-to-a-subset-of-your-data)
* [Multiple indices per model](#multiple-indices-per-model)
Expand Down Expand Up @@ -218,6 +219,46 @@ class ContactIndex(algoliaindex):
index_name = 'Enterprise'
```

## Field Preprocessing and Related objects

If you want to process a field before indexing it (e.g. capitalizing a `Contact`'s `name`), or if you want to index a [related object](https://docs.djangoproject.com/en/1.11/ref/models/relations/)'s attribute,
you need to define **proxy methods** for these fields.

### Models
```python
class Account(models.Model):
username = models.CharField(max_length=40)
service = models.CharField(max_length=40)

class Contact(models.Model):
name = models.CharField(max_length=40)
email = models.EmailField(max_length=60)
//...
accounts = models.ManyToManyField(Account)

def account_names(self):
return [str(account) for account in self.accounts.all()]

def account_ids(self):
return [account.id for account in self.accounts.all()]
```

### Index
```python
from algoliasearch_django import AlgoliaIndex


class ContactIndex(AlgoliaIndex):
fields = ('name', 'email', 'company', 'address', 'city', 'county',
'state', 'zip_code', 'phone', 'fax', 'web', 'followers', 'account_names', 'account_ids')

settings = {
'searchableAttributes': ['name', 'email', 'company', 'city', 'county', 'account_names',
}
```
- With this configuration, you can search for a `Contact` using its `Account` names
- You can use the associated `account_ids` at search-time to fetch more data from your model (you should **only proxy the fields relevant for search** to keep your records' size as small as possible)

## Index settings

We provide many ways to configure your index allowing you to tune your overall index relevancy.
Expand Down

0 comments on commit 0f70028

Please sign in to comment.