appengine-search icon indicating copy to clipboard operation
appengine-search copied to clipboard

How can you chain filters with a search?

Open palewire opened this issue 13 years ago • 0 comments

I'm building an AJAX search form that includes a search box and two pulldown filters with predefined options. If the user fills in the search and also uses the pull down, I'd like to chain that filter with your search. Wasn't sure how to pull it off right. But here's a hack I put together that adds a dict kwarg. Let me know what you think.

    @classmethod
    def search(cls, phrase, limit=10, keys_only=False, extra_filters=None):
        """Queries search indices for phrases using a merge-join.
        
        Use of this class method lets you easily restrict searches to a kind
        and retrieve entities or keys.

        Args:
            phrase: Search phrase (string)
            limit: Number of entities or keys to return.
            keys_only: If True, return only keys with title of parent entity.
        
        Returns:
            A list.  If keys_only is True, the list holds (key, title) tuples.
            If keys_only is False, the list holds Model instances.
        """
        key_list = Searchable.full_text_search(
                        phrase, limit=limit, kind=cls.kind(),
                        stemming=cls.INDEX_STEMMING, 
                        multi_word_literal=cls.INDEX_MULTI_WORD)
        if keys_only:
            logging.debug("key_list: %s", key_list)
            return key_list
        else:
            if extra_filters:
                query = cls.all()
                for field, value in extra_filters.items():
                    query = query.filter('%s =' % field, value)
                filtered_set = [query.ancestor(key_and_title[0]).get() for key_and_title in key_list]
                return [i for i in filtered_set if i]
            else:
                return [cls.get(key_and_title[0]) for key_and_title in key_list]

palewire avatar Dec 09 '10 18:12 palewire