Query – A search query

class Query(db, querystr)

Represents a search query on an opened Database.

A query selects and filters a subset of messages from the notmuch database we derive from.

Query provides an instance attribute sort, which contains the sort order (if specified via set_sort()) or None.

Any function in this class may throw an NotInitializedError in case the underlying query object was not set up correctly.


Do remember that as soon as we tear down this object, all underlying derived objects such as threads, messages, tags etc will be freed by the underlying library as well. Accessing these objects will lead to segfaults and other unexpected behavior. See above for more details.

  • db (Database) – An open database which we derive the Query from.
  • querystr (utf-8 encoded str or unicode) – The query string for the message.
create(db, querystr)

Creates a new query derived from a Database

This function is utilized by __init__() and usually does not need to be called directly.

  • db (Database) – Database to create the query from.
  • querystr (utf-8 encoded str or unicode) – The query string
NullPointerError if the query creation failed

(e.g. too little memory).

NotInitializedError if the underlying db was not



Defines constants that are used as the mode in which to open a database.

Sort by message date, oldest first.
Sort by message date, newest first.
Sort by email message ID.
Do not apply a special sort order (returns results in document id order).

Set the sort order future results will be delivered in

Parameters:sort – Sort order (see Query.SORT)

Instance attribute sort contains the sort order (see Query.SORT) if explicitly specified via set_sort(). By default it is set to None.


Add a tag that will be excluded from the query results by default.

This exclusion will be overridden if this tag appears explicitly in the query.

Parameters:tagname – Name of the tag to be excluded

Execute a query for threads

Execute a query for threads, returning a Threads iterator. The returned threads are owned by the query and as such, will only be valid until the Query is deleted.

The method sets Message.FLAG.MATCH for those messages that match the query. The method Message.get_flag() allows us to get the value of this flag.

Raises:NullPointerError if search_threads failed

Filter messages according to the query and return Messages in the defined sort order

Raises:NullPointerError if search_messages failed

This function performs a search and returns Xapian’s best guess as to the number of matching messages.

Returns:the estimated number of messages matching this query
Return type:int

This function performs a search and returns the number of unique thread IDs in the matching messages. This is the same as number of threads matching a search.

Note that this is a significantly heavier operation than meth:Query.count_messages.

Returns:the number of threads returned by this query
Return type:int