Package: brightnetwork-algoliasearch-django
The perfect starting point to integrateAlgoliawithin your Django projectDocumentation•Community Forum•Stack Overflow•Report a bug•SupportAPI DocumentationYou can find the full reference onAlgolia's website.SetupIntroductionInstallSetupQuick StartCommandsCommandsSearchSearchGeo-SearchGeo-SearchTagsTagsOptionsCustomobjectIDCustom index nameField Preprocessing and Related objectsIndex settingsRestrict indexing to a subset of your dataMultiple indices per modelTemporarily disable the auto-indexingAggregatorsAggregatorsTestsRun TestsSetupIntroductionThis package lets you easily integrate the Algolia Search API to yourDjangoproject. It's based on thealgoliasearch-client-pythonpackage.You might be interested in this sample Django application providing a typeahead.js based auto-completion and Google-like instant search:algoliasearch-django-exampleCompatible withPython 3.5+andDjango 2.2+Installpipinstallalgoliasearch-djangoSetupIn your Django settings, addalgoliasearch_djangotoINSTALLED_APPSand add these two settings:ALGOLIA={'APPLICATION_ID':'MyAppID','API_KEY':'MyApiKey'}There are several optional settings:INDEX_PREFIX: prefix all indices. Use it to separate different applications, likesite1_Productsandsite2_Products.INDEX_SUFFIX: suffix all indices. Use it to differentiate development and production environments, likeLocation_devandLocation_prod.AUTO_INDEXING: automatically synchronize the models with Algolia (default toTrue).RAISE_EXCEPTIONS: raise exceptions on network errors instead of logging them (default tosettings.DEBUG).Quick StartCreate anindex.pyinside each application that contains the models you want to index.
Inside this file, callalgoliasearch.register()for each of the models you want to index:# index.pyimportalgoliasearch_djangoasalgoliasearchfrom.modelsimportYourModelalgoliasearch.register(YourModel)By default, all the fields of your model will be used. You can configure the index by creating a subclass ofAlgoliaIndexand using theregisterdecorator:# index.pyfromalgoliasearch_djangoimportAlgoliaIndexfromalgoliasearch_django.decoratorsimportregisterfrom.modelsimportYourModel@register(YourModel)classYourModelIndex(AlgoliaIndex):fields=('name','date')geo_field='location'settings={'searchableAttributes':['name']}index_name='my_index'CommandsCommandspython manage.py algolia_reindex: reindex all the registered models. This command will first send all the record to a temporary index and then moves it.you can pass--indexparameter to reindex a given indexpython manage.py algolia_applysettings: (re)apply the index settings.python manage.py algolia_clearindex: clear the indexSearchSearchWe recommend using ourInstantSearch.js libraryto build your search
interface and perform search queries directly from the end-user browser without going through your server.However, if you want to search from your backend you can use theraw_search(YourModel, 'yourQuery', request_options)method.
It retrieves the raw JSON answer from the API, and accepts inrequest_optionsanysearch parameters.fromalgoliasearch_djangoimportraw_searchrequest_options={"hitsPerPage":5}response=raw_search(Contact,"jim",request_options)Geo-SearchGeo-SearchUse thegeo_fieldattribute to localize your record.geo_fieldshould be a callable that returns a tuple (latitude, longitude).classContact(models.model):name=models.CharField(max_length=20)lat=models.FloatField()lng=models.FloatField()deflocation(self):return(self.lat,self.lng)classContactIndex(AlgoliaIndex):fields='name'geo_field='location'algoliasearch.register(Contact,ContactIndex)TagsTagsUse thetagsattributes to add tags to your record. It can be a field or a callable.classArticleIndex(AlgoliaIndex):tags='category'At query time, specify{ tagFilters: 'tagvalue' }or{ tagFilters: ['tagvalue1', 'tagvalue2'] }as search parameters to restrict the result set to specific tags.OptionsCustomobjectIDYou can choose which field will be used as theobjectID. The field should be unique and can
be a string or integer. By default, we use thepkfield of the model.classArticleIndex(AlgoliaIndex):custom_objectID='post_id'Custom index nameYou can customize the index name. By default, the index name will be the name of the model class.classContactIndex(algoliaindex):index_name='Enterprise'Field Preprocessing and Related objectsIf you want to process a field before indexing it (e.g. capitalizing aContact'sname),
or if you want to index arelated object's
attribute, you need to defineproxy methodsfor these fields.ModelsclassAccount(models.Model):username=models.CharField(max_length=40)service=models.CharField(max_length=40)classContact(models.Model):name=models.CharField(max_length=40)email=models.EmailField(max_length=60)//...accounts=models.ManyToManyField(Account)defaccount_names(self):return[str(account)foraccountinself.accounts.all()]defaccount_ids(self):return[account.idforaccountinself.accounts.all()]Indexfromalgoliasearch_djangoimportAlgoliaIndexclassContactIndex(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 aContactusing itsAccountnamesYou can use the associatedaccount_idsat search-time to fetch more data from your
model (you shouldonly proxy the fields relevant for searchto keep your records' size
as small as possible)Index settingsWe provide many ways to configure your index allowing you to tune your overall index relevancy.
All the configuration is explained onour doc.classArticleIndex(AlgoliaIndex):settings={'searchableAttributes':['name','description','url'],'customRanking':['desc(vote_count)','asc(name)']}Restrict indexing to a subset of your dataYou can add constraints controlling if a record must be indexed or not.should_indexshould be a
callable that returns a boolean.classContact(models.model):name=models.CharField(max_length=20)age=models.IntegerField()defis_adult(self):return(self.age>=18)classContactIndex(AlgoliaIndex):should_index='is_adult'Multiple indices per modelIt is possible to have several indices for a single model.First, define all your indices that you want for a model:fromdjango.contrib.algoliasearchimportAlgoliaIndexclassMyModelIndex1(AlgoliaIndex):name='MyModelIndex1'...classMyModelIndex2(AlgoliaIndex):name='MyModelIndex2'...Then, define a meta model which will aggregate those indices:classMyModelMetaIndex(AlgoliaIndex):def__init__(self,model,client,settings):self.indices=[MyModelIndex1(model,client,settings),MyModelIndex2(model,client,settings),]defraw_search(self,query='',request_options=None):res={}forindexinself.indices:res[index.name]=index.raw_search(query,request_options)returnresdefupdate_records(self,qs,batch_size=1000,**kwargs):forindexinself.indices:index.update_records(qs,batch_size,**kwargs)defreindex_all(self,batch_size=1000):forindexinself.indices:index.reindex_all(batch_size)defset_settings(self):forindexinself.indices:index.set_settings()defclear_objects(self):forindexinself.indices:index.clear_objects()defsave_record(self,instance,update_fields=None,**kwargs):forindexinself.indices:index.save_record(instance,update_fields,**kwargs)defdelete_record(self,instance):forindexinself.indices:index.delete_record(instance)Finally, register thisAlgoliaIndexwith yourModel:importalgoliasearch_djangoasalgoliasearchalgoliasearch.register(MyModel,MyModelMetaIndex)Temporarily disable the auto-indexingIt is possible to temporarily disable the auto-indexing feature using thedisable_auto_indexingcontext decorator:fromalgoliasearch_django.decoratorsimportdisable_auto_indexing# Used as a context managerwithdisable_auto_indexing():MyModel.save()# Used as a decorator@disable_auto_indexing():my_method()# You can also specifiy for which model you want to disable the auto-indexingwithdisable_auto_indexing(MyModel):MyModel.save()MyOtherModel.save()AggregatorsAggregators allow multiple models to be included in a single index.importalgoliasearch_djangoasalgoliasearchmodels=[...]algoliasearch.register_aggregator(models)For more control,Aggregatorcan be subclassed in the same way asAlgoliaIndex:fromalgoliasearch_djangoimportAggregatorclassCustomAggregator(Aggregator)index_name="MyAggregatorIndex"...models=[...]algoliasearch.register_aggregator(models,CustomAggregator)TestsRun TestsTo run the tests, first find your Algolia application id and Admin API key (found on the Credentials page).ALGOLIA_APPLICATION_ID={APPLICATION_ID}ALGOLIA_API_KEY={ADMIN_API_KEY}toxTo override settings for some tests, use thesettings method:classOverrideSettingsTestCase(TestCase):defsetUp(self):withself.settings(ALGOLIA={'APPLICATION_ID':'foo','API_KEY':'bar','AUTO_INDEXING':False}):algolia_engine.reset(settings.ALGOLIA)deftearDown(self):algolia_engine.reset(settings.ALGOLIA)deftest_foo():# ...