Skip to content

Commit 0f70028

Browse files
committed
docs(README): Field preprocessing/Related objects, fixes #2
1 parent 448f6b3 commit 0f70028

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

README.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ You can find the full reference on [Algolia's website](https://www.algolia.com/d
5050

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

222+
## Field Preprocessing and Related objects
223+
224+
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,
225+
you need to define **proxy methods** for these fields.
226+
227+
### Models
228+
```python
229+
class Account(models.Model):
230+
username = models.CharField(max_length=40)
231+
service = models.CharField(max_length=40)
232+
233+
class Contact(models.Model):
234+
name = models.CharField(max_length=40)
235+
email = models.EmailField(max_length=60)
236+
//...
237+
accounts = models.ManyToManyField(Account)
238+
239+
def account_names(self):
240+
return [str(account) for account in self.accounts.all()]
241+
242+
def account_ids(self):
243+
return [account.id for account in self.accounts.all()]
244+
```
245+
246+
### Index
247+
```python
248+
from algoliasearch_django import AlgoliaIndex
249+
250+
251+
class ContactIndex(AlgoliaIndex):
252+
fields = ('name', 'email', 'company', 'address', 'city', 'county',
253+
'state', 'zip_code', 'phone', 'fax', 'web', 'followers', 'account_names', 'account_ids')
254+
255+
settings = {
256+
'searchableAttributes': ['name', 'email', 'company', 'city', 'county', 'account_names',
257+
}
258+
```
259+
- With this configuration, you can search for a `Contact` using its `Account` names
260+
- 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)
261+
221262
## Index settings
222263

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

0 commit comments

Comments
 (0)