CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pyes

Python Elastic Search driver providing a pythonic interface for interacting with ElasticSearch clusters

Pending
Overview
Eval results
Files

query-dsl.mddocs/

PyES Query DSL

Overview

The PyES Query DSL provides a comprehensive, pythonic interface for constructing ElasticSearch queries. All query classes inherit from the base Query class and can be combined using boolean logic to create complex search expressions.

Base Classes

Query Base Class

class Query:
    """
    Base class for all ElasticSearch queries.
    
    All query classes inherit from this base class and implement
    the serialize() method to convert to ElasticSearch JSON.
    """
    
    def serialize(self):
        """
        Convert query to ElasticSearch JSON format.
        
        Returns:
            dict: ElasticSearch query JSON
        """
        pass

Search Builder

class Search:
    """
    Main search query builder for constructing complete search requests.
    
    Provides methods to build complex search queries with filters,
    facets, aggregations, sorting, pagination, and highlighting.
    """
    
    def __init__(self, query=None):
        """
        Initialize search builder.
        
        Args:
            query (Query, optional): Initial query object
        """
        pass
    
    def query(self, query):
        """
        Set the query for search.
        
        Args:
            query (Query): Query object
            
        Returns:
            Search: Self for method chaining
        """
        pass
    
    def filter(self, filter):
        """
        Add filter to search.
        
        Args:
            filter (Filter): Filter object
            
        Returns:
            Search: Self for method chaining
        """
        pass
    
    def facet(self, facet):
        """
        Add facet to search.
        
        Args:
            facet (Facet): Facet object
            
        Returns:
            Search: Self for method chaining
        """
        pass
    
    def add_aggregation(self, agg):
        """
        Add aggregation to search.
        
        Args:
            agg (Agg): Aggregation object
            
        Returns:
            Search: Self for method chaining
        """
        pass
    
    def highlight(self, fields, **kwargs):
        """
        Add highlighting to search.
        
        Args:
            fields (list|dict): Fields to highlight
            **kwargs: Highlight options (pre_tags, post_tags, etc.)
            
        Returns:
            Search: Self for method chaining
        """
        pass
    
    def sort(self, field, order="asc"):
        """
        Add sorting to search results.
        
        Args:
            field (str): Field to sort by
            order (str): Sort order ('asc' or 'desc'). Default: 'asc'
            
        Returns:
            Search: Self for method chaining
        """
        pass
    
    def from_value(self, start):
        """
        Set starting position for results.
        
        Args:
            start (int): Starting position (0-based)
            
        Returns:
            Search: Self for method chaining
        """
        pass
    
    def size(self, size):
        """
        Set number of results to return.
        
        Args:
            size (int): Number of results
            
        Returns:
            Search: Self for method chaining
        """
        pass
    
    def suggest(self, suggest):
        """
        Add suggestions to search.
        
        Args:
            suggest (Suggest): Suggest object
            
        Returns:
            Search: Self for method chaining
        """
        pass

Basic Usage Examples

from pyes import Search, TermQuery, RangeQuery, BoolQuery

# Simple search with single query
search = Search(TermQuery("status", "published"))
results = es.search(search, indices=["blog"])

# Complex search with multiple components
search = Search(
    BoolQuery(
        must=[TermQuery("category", "tutorial")],
        filter=RangeQuery("published_date", gte="2023-01-01")
    )
).sort("published_date", "desc").size(20).from_value(0)

# Add highlighting
search.highlight(["title", "content"], 
                pre_tags=["<mark>"], 
                post_tags=["</mark>"])

results = es.search(search, indices=["blog"])

Core Query Types

Match All Query

class MatchAllQuery(Query):
    """
    Query that matches all documents.
    
    Useful as base query or for filtering-only searches.
    """
    
    def __init__(self, boost=None):
        """
        Initialize MatchAllQuery.
        
        Args:
            boost (float, optional): Query boost value
        """
        pass

# Match all documents
from pyes import MatchAllQuery

query = Search(MatchAllQuery())
results = es.search(query, indices=["blog"])

# Match all with boost
boosted_query = Search(MatchAllQuery(boost=2.0))

Term Query

class TermQuery(Query):
    """
    Query for exact term matching (not analyzed).
    
    Use for keyword fields, IDs, and exact matches.
    """
    
    def __init__(self, field, value, boost=None):
        """
        Initialize TermQuery.
        
        Args:
            field (str): Field name
            value (str|int|float|bool): Exact value to match
            boost (float, optional): Query boost value
        """
        pass

# Exact term matching
from pyes import TermQuery

# Match exact status
status_query = Search(TermQuery("status", "published"))

# Match numeric value
view_query = Search(TermQuery("view_count", 1000))

# Match boolean value  
featured_query = Search(TermQuery("featured", True))

# With boost
boosted_query = Search(TermQuery("priority", "high", boost=2.0))

Terms Query

class TermsQuery(Query):
    """
    Query for matching any of multiple exact terms.
    
    Equivalent to multiple TermQuery with OR logic.
    """
    
    def __init__(self, field, values, minimum_match=None, boost=None):
        """
        Initialize TermsQuery.
        
        Args:
            field (str): Field name
            values (list): List of exact values to match
            minimum_match (int, optional): Minimum number of terms that must match
            boost (float, optional): Query boost value
        """
        pass

# Match multiple categories
from pyes import TermsQuery

categories_query = Search(TermsQuery("category", ["tutorial", "guide", "reference"]))

# Match multiple tags with minimum match
tags_query = Search(TermsQuery("tags", ["python", "elasticsearch", "search"], 
                               minimum_match=2))

# Match multiple IDs
ids_query = Search(TermsQuery("_id", ["doc1", "doc2", "doc3"]))

Range Query

class RangeQuery(Query):
    """
    Query for range-based matching (numeric, date, or string ranges).
    """
    
    def __init__(self, field, from_value=None, to_value=None, 
                 include_lower=True, include_upper=True, 
                 boost=None, **kwargs):
        """
        Initialize RangeQuery.
        
        Args:
            field (str): Field name
            from_value: Lower bound value (use gte/gt kwargs instead)
            to_value: Upper bound value (use lte/lt kwargs instead)  
            include_lower (bool): Include lower bound. Default: True
            include_upper (bool): Include upper bound. Default: True
            boost (float, optional): Query boost value
            **kwargs: Range parameters (gte, gt, lte, lt)
        """
        pass

# Date range queries
from pyes import RangeQuery

# Published this year
this_year_query = Search(RangeQuery("published_date", gte="2023-01-01"))

# Date range (between dates)
date_range_query = Search(RangeQuery("published_date", 
                                    gte="2023-01-01", 
                                    lt="2024-01-01"))

# Numeric range
view_range_query = Search(RangeQuery("view_count", gte=100, lte=1000))

# String range (alphabetical)
title_range_query = Search(RangeQuery("title.keyword", gte="A", lt="M"))

Boolean Query

Complex Query Logic

class BoolQuery(Query):
    """
    Boolean combination of multiple queries with must/should/must_not/filter clauses.
    
    Provides full boolean logic for complex search requirements.
    """
    
    def __init__(self, must=None, should=None, must_not=None, filter=None,
                 minimum_should_match=None, boost=None, disable_coord=None):
        """
        Initialize BoolQuery.
        
        Args:
            must (Query|list): Queries that must match (AND logic, affects scoring)
            should (Query|list): Queries that should match (OR logic, affects scoring)  
            must_not (Query|list): Queries that must not match (NOT logic)
            filter (Query|list): Queries for filtering (no scoring impact)
            minimum_should_match (int|str): Minimum should queries that must match
            boost (float, optional): Query boost value
            disable_coord (bool): Disable coordination factor
        """
        pass

# Complex boolean search
from pyes import BoolQuery, TermQuery, RangeQuery, MatchQuery

# Blog posts that must be published, should contain python or elasticsearch,
# must not be drafts, and filtered by date
complex_query = Search(
    BoolQuery(
        must=[
            TermQuery("status", "published"),
            MatchQuery("content", "programming")
        ],
        should=[
            TermQuery("tags", "python"),
            TermQuery("tags", "elasticsearch"), 
            TermQuery("tags", "tutorial")
        ],
        must_not=[
            TermQuery("category", "draft"),
            TermQuery("author", "spam_user")
        ],
        filter=[
            RangeQuery("published_date", gte="2023-01-01"),
            RangeQuery("view_count", gte=10)
        ],
        minimum_should_match=1  # At least one should clause must match
    )
)

results = es.search(complex_query, indices=["blog"])

Text Search Queries

Match Query

class MatchQuery(Query):
    """
    Full-text search query with analysis and relevance scoring.
    
    Analyzes input text and matches against analyzed field content.
    """
    
    def __init__(self, field, query, boost=None, analyzer=None, 
                 fuzziness=None, prefix_length=None, max_expansions=None,
                 operator="OR", minimum_should_match=None, zero_terms_query="NONE"):
        """
        Initialize MatchQuery.
        
        Args:
            field (str): Field name to search
            query (str): Query text to match
            boost (float, optional): Query boost value
            analyzer (str, optional): Analyzer to use for query text
            fuzziness (str|int, optional): Fuzziness for matching (AUTO, 0, 1, 2)
            prefix_length (int, optional): Number of initial characters not fuzzified
            max_expansions (int, optional): Maximum term expansions for fuzzy matching
            operator (str): Boolean operator for terms (OR, AND). Default: "OR"
            minimum_should_match (str|int): Minimum terms that should match
            zero_terms_query (str): Behavior when all terms are stop words
        """
        pass

# Full-text search
from pyes import MatchQuery

# Basic text search
search_query = Search(MatchQuery("content", "python elasticsearch tutorial"))

# Match with specific operator (all terms must match)
strict_query = Search(MatchQuery("title", "python programming", operator="AND"))

# Fuzzy matching for typos
fuzzy_query = Search(MatchQuery("content", "elsticsearch", fuzziness="AUTO"))

# With minimum should match
flexible_query = Search(MatchQuery("content", "python tutorial guide advanced", 
                                  minimum_should_match="75%"))

Multi Match Query

class MultiMatchQuery(Query):
    """
    Match query across multiple fields with various matching strategies.
    """
    
    def __init__(self, query, fields, boost=None, type="best_fields", 
                 analyzer=None, fuzziness=None, prefix_length=None,
                 max_expansions=None, operator="OR", minimum_should_match=None):
        """
        Initialize MultiMatchQuery.
        
        Args:
            query (str): Query text
            fields (list): List of fields to search across
            boost (float, optional): Query boost value
            type (str): Multi-match type (best_fields, most_fields, cross_fields, 
                       phrase, phrase_prefix). Default: "best_fields"
            analyzer (str, optional): Analyzer for query text
            fuzziness (str|int, optional): Fuzziness level
            prefix_length (int, optional): Prefix length for fuzzy matching
            max_expansions (int, optional): Max expansions for fuzzy
            operator (str): Boolean operator (OR, AND). Default: "OR"
            minimum_should_match (str|int): Minimum should match
        """
        pass

# Multi-field search
from pyes import MultiMatchQuery

# Search across title and content
multi_query = Search(MultiMatchQuery("python programming", 
                                   ["title^2", "content", "tags"]))

# Cross-fields search (terms can be in different fields)
cross_query = Search(MultiMatchQuery("john smith", 
                                   ["first_name", "last_name"],
                                   type="cross_fields"))

# Phrase matching across fields
phrase_query = Search(MultiMatchQuery("machine learning", 
                                    ["title", "content", "abstract"],
                                    type="phrase"))

Query String Query

class QueryStringQuery(Query):
    """
    Lucene query string syntax parser for advanced search expressions.
    
    Supports field-specific search, boolean operators, wildcards, 
    ranges, and phrase queries in a single string.
    """
    
    def __init__(self, query, default_field=None, fields=None, 
                 default_operator="OR", analyzer=None, allow_leading_wildcard=True,
                 lowercase_expanded_terms=True, enable_position_increments=True,
                 fuzzy_max_expansions=50, fuzziness=None, fuzzy_prefix_length=0,
                 phrase_slop=0, boost=None, analyze_wildcard=False,
                 auto_generate_phrase_queries=False, minimum_should_match=None):
        """
        Initialize QueryStringQuery.
        
        Args:
            query (str): Lucene query string
            default_field (str, optional): Default field when none specified
            fields (list, optional): Fields to search when none specified in query
            default_operator (str): Default operator (OR, AND). Default: "OR"
            analyzer (str, optional): Analyzer for query
            allow_leading_wildcard (bool): Allow wildcards at start. Default: True
            lowercase_expanded_terms (bool): Lowercase wildcard/fuzzy terms. Default: True
            enable_position_increments (bool): Enable position increments. Default: True
            fuzzy_max_expansions (int): Max fuzzy expansions. Default: 50
            fuzziness (str|int, optional): Fuzzy matching level
            fuzzy_prefix_length (int): Fuzzy prefix length. Default: 0
            phrase_slop (int): Phrase slop for proximity. Default: 0
            boost (float, optional): Query boost
            analyze_wildcard (bool): Analyze wildcard queries. Default: False
            auto_generate_phrase_queries (bool): Auto phrase detection. Default: False
            minimum_should_match (str|int): Minimum should match
        """
        pass

# Lucene query string syntax
from pyes import QueryStringQuery

# Complex query string with field-specific search
lucene_query = Search(QueryStringQuery(
    'title:"python tutorial" AND (tags:elasticsearch OR tags:search) AND published_date:[2023-01-01 TO *]'
))

# Search with wildcards and fuzzy matching
wildcard_query = Search(QueryStringQuery(
    'title:python* AND content:search~2',  # Wildcard and fuzzy
    default_operator="AND"
))

# Multi-field query string
multi_field_query = Search(QueryStringQuery(
    'programming tutorial',
    fields=["title^2", "content", "tags"],
    minimum_should_match="50%"
))

Fuzzy and Similarity Queries

Fuzzy Query

class FuzzyQuery(Query):
    """
    Fuzzy term matching for handling typos and misspellings.
    """
    
    def __init__(self, field, value, boost=None, fuzziness="AUTO", 
                 prefix_length=0, max_expansions=50):
        """
        Initialize FuzzyQuery.
        
        Args:
            field (str): Field name
            value (str): Term to match fuzzily  
            boost (float, optional): Query boost
            fuzziness (str|int): Fuzziness level (AUTO, 0, 1, 2). Default: "AUTO"
            prefix_length (int): Characters at start that must match exactly. Default: 0
            max_expansions (int): Maximum term expansions. Default: 50
        """
        pass

# Fuzzy term matching
from pyes import FuzzyQuery

# Handle typos in search
fuzzy_search = Search(FuzzyQuery("title", "elastcsearch", fuzziness=2))

# Auto-fuzziness based on term length
auto_fuzzy = Search(FuzzyQuery("content", "progamming", fuzziness="AUTO"))

More Like This Query

class MoreLikeThisQuery(Query):
    """
    Find documents similar to provided text or documents.
    """
    
    def __init__(self, fields, like_text=None, docs=None, ids=None,
                 min_term_freq=2, max_query_terms=25, stop_words=None,
                 min_doc_freq=5, max_doc_freq=None, min_word_len=0,
                 max_word_len=0, analyzer=None, boost=None, include=True):
        """
        Initialize MoreLikeThisQuery.
        
        Args:
            fields (list): Fields to use for similarity
            like_text (str, optional): Text to find similar documents for
            docs (list, optional): Documents to find similar documents for
            ids (list, optional): Document IDs to find similar documents for
            min_term_freq (int): Minimum term frequency. Default: 2
            max_query_terms (int): Maximum query terms. Default: 25
            stop_words (list, optional): Stop words to ignore
            min_doc_freq (int): Minimum document frequency. Default: 5
            max_doc_freq (int, optional): Maximum document frequency
            min_word_len (int): Minimum word length. Default: 0
            max_word_len (int): Maximum word length. Default: 0  
            analyzer (str, optional): Analyzer to use
            boost (float, optional): Query boost
            include (bool): Include the original document. Default: True
        """
        pass

# Find similar documents
from pyes import MoreLikeThisQuery

# Similar to provided text
similar_text = Search(MoreLikeThisQuery(
    fields=["title", "content"],
    like_text="python elasticsearch tutorial guide",
    min_term_freq=1,
    max_query_terms=12
))

# Similar to specific documents  
similar_docs = Search(MoreLikeThisQuery(
    fields=["content"],
    ids=["doc1", "doc2"],
    min_doc_freq=2,
    include=False  # Exclude original documents
))

Specialized Queries

Prefix Query

class PrefixQuery(Query):
    """
    Match documents with terms that start with specified prefix.
    """
    
    def __init__(self, field, prefix, boost=None):
        """
        Initialize PrefixQuery.
        
        Args:
            field (str): Field name
            prefix (str): Prefix to match
            boost (float, optional): Query boost
        """
        pass

# Prefix matching for autocomplete
from pyes import PrefixQuery

# Find titles starting with "python"
prefix_query = Search(PrefixQuery("title.keyword", "python"))

# Tag autocomplete
tag_autocomplete = Search(PrefixQuery("tags", "elastic"))

Wildcard Query

class WildcardQuery(Query):
    """
    Wildcard pattern matching (* and ? wildcards).
    """
    
    def __init__(self, field, value, boost=None):
        """
        Initialize WildcardQuery.
        
        Args:
            field (str): Field name
            value (str): Wildcard pattern (* = any chars, ? = single char)
            boost (float, optional): Query boost
        """
        pass

# Wildcard pattern matching
from pyes import WildcardQuery

# Match any .py files
file_query = Search(WildcardQuery("filename", "*.py"))

# Phone number patterns
phone_query = Search(WildcardQuery("phone", "555-????"))

Regular Expression Query

class RegexTermQuery(Query):
    """
    Regular expression pattern matching.
    """
    
    def __init__(self, field, value, boost=None, flags=None):
        """
        Initialize RegexTermQuery.
        
        Args:
            field (str): Field name  
            value (str): Regular expression pattern
            boost (float, optional): Query boost
            flags (str, optional): Regex flags
        """
        pass

# Regular expression matching
from pyes import RegexTermQuery

# Email pattern matching
email_query = Search(RegexTermQuery("email", r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"))

# Version number patterns
version_query = Search(RegexTermQuery("version", r"[0-9]+\.[0-9]+\.[0-9]+"))

IDs Query

class IdsQuery(Query):
    """
    Match documents by their IDs.
    """
    
    def __init__(self, values, types=None, boost=None):
        """
        Initialize IdsQuery.
        
        Args:
            values (list): List of document IDs
            types (list, optional): Document types to search in
            boost (float, optional): Query boost
        """
        pass

# Match specific document IDs
from pyes import IdsQuery

# Get specific documents
ids_query = Search(IdsQuery(["doc1", "doc2", "doc3"]))

# IDs within specific types
typed_ids_query = Search(IdsQuery(["post1", "post2"], types=["blog_post"]))

Scoring and Boosting Queries

Constant Score Query

class ConstantScoreQuery(Query):
    """
    Wrap query or filter with constant score (no relevance calculation).
    """
    
    def __init__(self, query=None, filter=None, boost=1.0):
        """
        Initialize ConstantScoreQuery.
        
        Args:
            query (Query, optional): Query to wrap
            filter (Filter, optional): Filter to wrap  
            boost (float): Constant score value. Default: 1.0
        """
        pass

# Constant scoring for filters
from pyes import ConstantScoreQuery, TermFilter

# All matching documents get same score
constant_query = Search(ConstantScoreQuery(
    filter=TermFilter("category", "tutorial"),
    boost=1.5
))

Function Score Query

class FunctionScoreQuery(Query):
    """
    Modify document scores using functions (field values, scripts, etc.).
    """
    
    def __init__(self, query, functions=None, score_mode="multiply",
                 boost_mode="multiply", max_boost=None, boost=None):
        """
        Initialize FunctionScoreQuery.
        
        Args:
            query (Query): Base query
            functions (list): List of scoring functions
            score_mode (str): How to combine function scores. Default: "multiply"  
            boost_mode (str): How to combine with query score. Default: "multiply"
            max_boost (float, optional): Maximum boost value
            boost (float, optional): Query boost
        """
        pass

# Custom scoring based on popularity
from pyes import FunctionScoreQuery, MatchQuery

# Boost popular documents
popularity_query = Search(FunctionScoreQuery(
    query=MatchQuery("content", "python tutorial"),
    functions=[
        {
            "field_value_factor": {
                "field": "popularity_score",
                "factor": 1.5,
                "modifier": "log1p"
            }
        },
        {
            "gauss": {
                "published_date": {
                    "origin": "2023-12-01",
                    "scale": "30d",
                    "decay": 0.5
                }
            }
        }
    ],
    score_mode="sum",
    boost_mode="multiply"
))

Hierarchical Queries

Parent-Child Queries

class HasChildQuery(Query):
    """
    Match parent documents that have child documents matching the query.
    """
    
    def __init__(self, type, query, score_type="none", min_children=None, 
                 max_children=None, boost=None):
        """
        Initialize HasChildQuery.
        
        Args:
            type (str): Child document type
            query (Query): Query for child documents
            score_type (str): How child scores affect parent (none, max, sum, avg)
            min_children (int, optional): Minimum matching children required
            max_children (int, optional): Maximum matching children allowed
            boost (float, optional): Query boost
        """
        pass

class HasParentQuery(Query):
    """
    Match child documents that have parent documents matching the query.
    """
    
    def __init__(self, parent_type, query, score_type="none", boost=None):
        """
        Initialize HasParentQuery.
        
        Args:
            parent_type (str): Parent document type
            query (Query): Query for parent documents  
            score_type (str): How parent scores affect child (none, score)
            boost (float, optional): Query boost
        """
        pass

# Parent-child relationships
from pyes import HasChildQuery, HasParentQuery, TermQuery

# Find blog posts with approved comments
posts_with_comments = Search(HasChildQuery(
    type="comment",
    query=TermQuery("status", "approved"),
    min_children=1,
    score_type="max"  # Use highest child score
))

# Find comments on featured posts
comments_on_featured = Search(HasParentQuery(
    parent_type="post",
    query=TermQuery("featured", True)
))

Nested Query

class NestedQuery(Query):
    """
    Query nested objects within documents.
    """
    
    def __init__(self, path, query, score_mode="avg", boost=None):
        """
        Initialize NestedQuery.
        
        Args:
            path (str): Path to nested object
            query (Query): Query for nested objects
            score_mode (str): Score mode (avg, max, sum, none). Default: "avg"
            boost (float, optional): Query boost
        """
        pass

# Nested object queries
from pyes import NestedQuery, BoolQuery, RangeQuery

# Query nested product variants
nested_query = Search(NestedQuery(
    path="variants",
    query=BoolQuery(
        must=[
            TermQuery("variants.color", "red"),
            RangeQuery("variants.price", lt=100)
        ]
    ),
    score_mode="max"
))

Span Queries

Span Term Query

class SpanTermQuery(Query):
    """
    Span query for exact term matching with position information.
    """
    
    def __init__(self, field, value, boost=None):
        """
        Initialize SpanTermQuery.
        
        Args:
            field (str): Field name
            value (str): Term to match
            boost (float, optional): Query boost
        """
        pass

class SpanNearQuery(Query):
    """
    Match spans that are near each other (proximity search).
    """
    
    def __init__(self, clauses, slop, in_order=True, boost=None):
        """
        Initialize SpanNearQuery.
        
        Args:
            clauses (list): List of span queries
            slop (int): Maximum distance between spans
            in_order (bool): Whether spans must be in order. Default: True
            boost (float, optional): Query boost
        """
        pass

# Proximity search with span queries
from pyes import SpanNearQuery, SpanTermQuery

# Find "python" near "elasticsearch" within 5 positions
proximity_query = Search(SpanNearQuery(
    clauses=[
        SpanTermQuery("content", "python"),
        SpanTermQuery("content", "elasticsearch")
    ],
    slop=5,
    in_order=False
))

Suggestion Queries

Suggest Object

class Suggest:
    """
    Container for multiple suggestion requests.
    """
    
    def __init__(self):
        pass
    
    def add(self, text, name, field, type='term', size=None, params=None):
        """
        Add suggestion request.
        
        Args:
            text (str): Text to get suggestions for
            name (str): Suggestion name
            field (str): Field to suggest from
            type (str): Suggestion type (term, phrase, completion). Default: 'term'
            size (int, optional): Number of suggestions
            params (dict, optional): Additional parameters
        """
        pass
    
    def add_term(self, text, name, field, size=None, params=None):
        """Add term suggestion."""
        pass
    
    def add_phrase(self, text, name, field, size=None, params=None):
        """Add phrase suggestion."""  
        pass
    
    def add_completion(self, text, name, field, size=None, params=None):
        """Add completion suggestion."""
        pass

# Multiple suggestion types
from pyes import Suggest

suggest = Suggest()
suggest.add_term("pythno", "term_suggest", "title")  # Typo correction
suggest.add_phrase("elatic search", "phrase_suggest", "content")  # Phrase correction
suggest.add_completion("pyth", "completion_suggest", "tags.suggest")  # Autocomplete

suggestions = es.suggest_from_object(suggest, indices=["blog"])

Advanced Query Patterns

Filtered Query (Deprecated but Supported)

class FilteredQuery(Query):
    """
    Combine query with filter (deprecated - use BoolQuery with filter instead).
    """
    
    def __init__(self, query, filter, boost=None):
        """
        Initialize FilteredQuery.
        
        Args:
            query (Query): Main query
            filter (Filter): Filter to apply
            boost (float, optional): Query boost
        """
        pass

# Legacy filtered query (use BoolQuery instead)
from pyes import FilteredQuery, MatchQuery, TermFilter

# Deprecated approach
filtered = Search(FilteredQuery(
    query=MatchQuery("content", "python"),
    filter=TermFilter("status", "published")
))

# Recommended approach using BoolQuery
recommended = Search(BoolQuery(
    must=[MatchQuery("content", "python")],
    filter=[TermFilter("status", "published")]
))

Query Composition Patterns

# Complex query building patterns
from pyes import Search, BoolQuery, TermQuery, RangeQuery, MatchQuery, FunctionScoreQuery

def build_blog_search_query(text=None, categories=None, date_range=None, 
                           author=None, min_views=None, boost_featured=False):
    """
    Build complex blog search query with multiple optional parameters.
    """
    
    # Start with base query
    must_clauses = []
    filter_clauses = []
    should_clauses = []
    
    # Add text search if provided
    if text:
        must_clauses.append(MatchQuery("content", text))
    
    # Filter by categories
    if categories:
        if isinstance(categories, list):
            filter_clauses.append(TermsQuery("category", categories))
        else:
            filter_clauses.append(TermQuery("category", categories))
    
    # Date range filter
    if date_range:
        filter_clauses.append(RangeQuery("published_date", **date_range))
    
    # Author filter
    if author:
        filter_clauses.append(TermQuery("author", author))
    
    # Minimum views filter
    if min_views:
        filter_clauses.append(RangeQuery("view_count", gte=min_views))
    
    # Build boolean query
    bool_query = BoolQuery()
    if must_clauses:
        bool_query.must = must_clauses
    if should_clauses:
        bool_query.should = should_clauses
    if filter_clauses:
        bool_query.filter = filter_clauses
    
    # Add boost for featured posts
    if boost_featured:
        bool_query.should = bool_query.should or []
        bool_query.should.append(TermQuery("featured", True, boost=2.0))
    
    return Search(bool_query)

# Usage examples
search1 = build_blog_search_query(
    text="python tutorial",
    categories=["programming", "tutorial"],
    date_range={"gte": "2023-01-01"},
    min_views=100,
    boost_featured=True
)

search2 = build_blog_search_query(
    author="john_doe",
    date_range={"gte": "2023-06-01", "lte": "2023-12-31"}
)

The PyES Query DSL provides comprehensive querying capabilities with full ElasticSearch feature support, allowing construction of simple to highly complex search expressions with proper scoring, filtering, and boolean logic.

Install with Tessl CLI

npx tessl i tessl/pypi-pyes

docs

bulk-operations.md

client.md

facets-aggregations.md

filters.md

index.md

mappings.md

query-dsl.md

rivers.md

tile.json