Skip to content

Instantly share code, notes, and snippets.

@kaedroho
Created January 25, 2016 10:16
Show Gist options
  • Save kaedroho/4239f40e8679665fc484 to your computer and use it in GitHub Desktop.
Save kaedroho/4239f40e8679665fc484 to your computer and use it in GitHub Desktop.
from django.utils import timezone
from wagtail.wagtailsearch.backends.elasticsearch import ElasticSearch, ElasticSearchQuery
from wagtail.wagtailcore.models import Page
from wagtail.wagtailimages.models import AbstractImage
from wagtail.wagtaildocs.models import Document
class ElasticSearchQueryWithRecency(ElasticSearchQuery):
"""
An elasticsearch query class that takes recency into account
"""
def get_inner_query(self):
if issubclass(self.queryset.model, Page):
created_at_field = 'first_published_at_filter'
elif issubclass(self.queryset.model, (AbstractImage, Document)):
created_at_field = 'created_at_filter'
else:
created_at_field = None
if created_at_field:
return {
"function_score": {
"query": super().get_inner_query(),
"functions": [
{
"gauss": {
created_at_field: {
"origin": timezone.now(),
"offset": "7d",
"scale": "100d",
"decay": 0.5,
}
}
}
]
}
}
else:
return super().get_inner_query()
class CustomElasticSearch(ElasticSearch):
search_query_class = ElasticSearchQueryWithRecency
SearchBackend = CustomElasticSearch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment