Skip to content

Instantly share code, notes, and snippets.

@kaedroho
Created March 4, 2015 11:00
Show Gist options
  • Save kaedroho/3f7d21c4495b8ef1010a to your computer and use it in GitHub Desktop.
Save kaedroho/3f7d21c4495b8ef1010a to your computer and use it in GitHub Desktop.
from wagtail.wagtailsearch.backends import get_search_backend
from wagtail.wagtailsearch.backends.elasticsearch import ElasticSearchResults
from wagtail.wagtailcore.models import Page
s = get_search_backend()
class AwesomeQuery(object):
def __init__(self, search_query, campaigns, languages,
countries, content_types):
self.search_query = search_query
self.campaigns = campaigns
self.languages = languages
self.countries = countries
self.content_types = content_types
@property
def queryset(self):
# Just has to return any queryset of Page
# This is used by ElasticSearchResults to find the model to return
return Page.objects.all()
def to_es(self):
# It chokes on empty lists and strings
# Search query
if self.search_query:
query = {
'multi_match': {
'query': self.search_query,
'fields': ['_all', '_partials'],
}
}
else:
query = {
'match_all': {}
}
filters = [
{
"prefix": {
"content_type": "wagtailcore_page"
# To filter by content type: append _myapp_mymodel to page
},
},
{
"term": {
"live_filter": True
}
},
]
taxonomy_filters = []
if self.campaigns:
taxonomy_filters.append({'terms': {'campaign_snippets_filter': self.campaigns}})
if self.languages:
taxonomy_filters.append({'terms': {'language_filter': self.languages}})
if self.countries:
taxonomy_filters.append({'terms': {'countries_filter': self.countries}})
if self.content_types:
for content_type in self.content_types:
taxonomy_filters.append({"prefix": {"content_type": "wagtailcore_page_" + content_type}})
else:
filters.append({"prefix": {"content_type": "wagtailcore_page"}})
if taxonomy_filters:
filters.append({"or": taxonomy_filters})
return {
"filtered": {
"query": query,
"filter": {
"and": filters
}
}
}
def search(search_query, campaigns, languages, countries, content_types):
# campaigns should always be a list
return ElasticSearchResults(s, AwesomeQuery(search_query, campaigns, languages, countries, content_types))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment