Previous Next

Query Construction API

In addition to parsing a string query automatically it's also possible to construct them with the query API.

User queries can be combined with queries created through the query API. Simply use the query parser to construct a query from a string:

$query = Zend_Search_Lucene_Search_QueryParser::parse($queryString);

Query Parser Exceptions

The query parser may generate two types of exceptions:

  • Zend_Search_Lucene_Exception is thrown if something goes wrong in the query parser itself.

  • Zend_Search_Lucene_Search_QueryParserException is thrown when there is an error in the query syntax.

It's a good idea to catch Zend_Search_Lucene_Search_QueryParserExceptions and handle it appropriately:
try {
    $query = Zend_Search_Lucene_Search_QueryParser::parse($queryString);
} catch (Zend_Search_Lucene_Search_QueryParserException $e) {
    echo "Query syntax error: " . $e->getMessage() . "\n";
}

The same technique should be used for the find() method of a Zend_Search_Lucene object.

Starting in 1.5, query parsing exceptions are suppressed by default. If query doesn't conform query language, then it's tokenized using current default analyzer and all tokenized terms are used for searching. Use Zend_Search_Lucene_Search_QueryParser::dontSuppressQueryParsingExceptions() method to turn exceptions on. Zend_Search_Lucene_Search_QueryParser::suppressQueryParsingExceptions() and Zend_Search_Lucene_Search_QueryParser::queryParsingExceptionsSuppressed() methods are also intended to manage exceptions handling behavior.

Term Query

Term queries can be used for searching with a single term.

Query string:

word1

or

Query construction by API:

$term  = new Zend_Search_Lucene_Index_Term('word1', 'field1');
$query = new Zend_Search_Lucene_Search_Query_Term($term);
$hits  = $index->find($query);

The term field is optional. Zend_Search_Lucene searches through all indexed fields in each document if the field is not specified:

// Search for 'word1' in all indexed fields
$term  = new Zend_Search_Lucene_Index_Term('word1');
$query = new Zend_Search_Lucene_Search_Query_Term($term);
$hits  = $index->find($query);

Multi-Term Query

Multi-term queries can be used for searching with a set of terms.

Each term in a set can be defined as required, prohibited, or neither.

  • required means that documents not matching this term will not match the query;

  • prohibited means that documents matching this term will not match the query;

  • neither, in which case matched documents are neither prohibited from, nor required to, match the term. A document must match at least 1 term, however, to match the query.

If optional terms are added to a query with required terms, both queries will have the same result set but the optional terms may affect the score of the matched documents.

Both search methods can be used for multi-term queries.

Query string:

+word1 author:word2 -word3
  • '+' is used to define a required term.

  • '-' is used to define a prohibited term.

  • 'field:' prefix is used to indicate a document field for a search. If it's omitted, then all fields are searched.

or

Query construction by API:

$query = new Zend_Search_Lucene_Search_Query_MultiTerm();

$query->addTerm(new Zend_Search_Lucene_Index_Term('word1'), true);
$query->addTerm(new Zend_Search_Lucene_Index_Term('word2', 'author'),
                null);
$query->addTerm(new Zend_Search_Lucene_Index_Term('word3'), false);

$hits  = $index->find($query);

It's also possible to specify terms list within MultiTerm query constructor:

$terms = array(new Zend_Search_Lucene_Index_Term('word1'),
               new Zend_Search_Lucene_Index_Term('word2', 'author'),
               new Zend_Search_Lucene_Index_Term('word3'));
$signs = array(true, null, false);

$query = new Zend_Search_Lucene_Search_Query_MultiTerm($terms, $signs);

$hits  = $index->find($query);

The $signs array contains information about the term type:

  • true is used to define required term.

  • false is used to define prohibited term.

  • null is used to define a term that is neither required nor prohibited.

Boolean Query

Boolean queries allow to construct query using other queries and boolean operators.

Each subquery in a set can be defined as required, prohibited, or optional.

  • required means that documents not matching this subquery will not match the query;

  • prohibited means that documents matching this subquery will not match the query;

  • optional, in which case matched documents are neither prohibited from, nor required to, match the subquery. A document must match at least 1 subquery, however, to match the query.

If optional subqueries are added to a query with required subqueries, both queries will have the same result set but the optional subqueries may affect the score of the matched documents.

Both search methods can be used for boolean queries.

Query string:

+(word1 word2 word3) author:(word4 word5) -word6
  • '+' is used to define a required subquery.

  • '-' is used to define a prohibited subquery.

  • 'field:' prefix is used to indicate a document field for a search. If it's omitted, then all fields are searched.

or

Query construction by API:

$query = new Zend_Search_Lucene_Search_Query_Boolean();

$subquery1 = new Zend_Search_Lucene_Search_Query_MultiTerm();
$subquery1->addTerm(new Zend_Search_Lucene_Index_Term('word1'));
$subquery1->addTerm(new Zend_Search_Lucene_Index_Term('word2'));
$subquery1->addTerm(new Zend_Search_Lucene_Index_Term('word3'));

$subquery2 = new Zend_Search_Lucene_Search_Query_MultiTerm();
$subquery2->addTerm(new Zend_Search_Lucene_Index_Term('word4', 'author'));
$subquery2->addTerm(new Zend_Search_Lucene_Index_Term('word5', 'author'));

$term6 = new Zend_Search_Lucene_Index_Term('word6');
$subquery3 = new Zend_Search_Lucene_Search_Query_Term($term6);

$query->addSubquery($subquery1, true  /* required */);
$query->addSubquery($subquery2, null  /* optional */);
$query->addSubquery($subquery3, false /* prohibited */);

$hits  = $index->find($query);

It's also possible to specify subqueries list within Boolean query constructor:

...
$subqueries = array($subquery1, $subquery2, $subquery3);
$signs = array(true, null, false);

$query = new Zend_Search_Lucene_Search_Query_Boolean($subqueries, $signs);

$hits  = $index->find($query);

The $signs array contains information about the subquery type:

  • true is used to define required subquery.

  • false is used to define prohibited subquery.

  • null is used to define a subquery that is neither required nor prohibited.

Each query which uses boolean operators can be rewritten using signs notation and constructed using API. For example:

word1 AND (word2 AND word3 AND NOT word4) OR word5
is equivalent to
(+(word1) +(+word2 +word3 -word4)) (word5)

Wildcard Query

Wildcard queries can be used to search for documents containing strings matching specified patterns.

The '?' symbol is used as a single character wildcard.

The '*' symbol is used as a multiple character wildcard.

Query string:

field1:test*

or

Query construction by API:

$pattern = new Zend_Search_Lucene_Index_Term('test*', 'field1');
$query = new Zend_Search_Lucene_Search_Query_Wildcard($pattern);
$hits  = $index->find($query);

The term field is optional. Zend_Search_Lucene searches through all fields on each document if a field is not specified:

$pattern = new Zend_Search_Lucene_Index_Term('test*');
$query = new Zend_Search_Lucene_Search_Query_Wildcard($pattern);
$hits  = $index->find($query);

Fuzzy Query

Fuzzy queries can be used to search for documents containing strings matching terms similar to specified term.

Query string:

field1:test~
This query matches documents containing 'test' 'text' 'best' words and others.

or

Query construction by API:

$term = new Zend_Search_Lucene_Index_Term('test', 'field1');
$query = new Zend_Search_Lucene_Search_Query_Fuzzy($term);
$hits  = $index->find($query);

Optional similarity can be specified after "~" sign.

Query string:

field1:test~0.4

or

Query construction by API:

$term = new Zend_Search_Lucene_Index_Term('test', 'field1');
$query = new Zend_Search_Lucene_Search_Query_Fuzzy($term, 0.4);
$hits  = $index->find($query);

The term field is optional. Zend_Search_Lucene searches through all fields on each document if a field is not specified:

$term = new Zend_Search_Lucene_Index_Term('test');
$query = new Zend_Search_Lucene_Search_Query_Fuzzy($term);
$hits  = $index->find($query);

Phrase Query

Phrase Queries can be used to search for a phrase within documents.

Phrase Queries are very flexible and allow the user or developer to search for exact phrases as well as 'sloppy' phrases.

Phrases can also contain gaps or terms in the same places; they can be generated by the analyzer for different purposes. For example, a term can be duplicated to increase the term its weight, or several synonyms can be placed into a single position.

$query1 = new Zend_Search_Lucene_Search_Query_Phrase();

// Add 'word1' at 0 relative position.
$query1->addTerm(new Zend_Search_Lucene_Index_Term('word1'));

// Add 'word2' at 1 relative position.
$query1->addTerm(new Zend_Search_Lucene_Index_Term('word2'));

// Add 'word3' at 3 relative position.
$query1->addTerm(new Zend_Search_Lucene_Index_Term('word3'), 3);

...

$query2 = new Zend_Search_Lucene_Search_Query_Phrase(
                array('word1', 'word2', 'word3'), array(0,1,3));

...

// Query without a gap.
$query3 = new Zend_Search_Lucene_Search_Query_Phrase(
                array('word1', 'word2', 'word3'));

...

$query4 = new Zend_Search_Lucene_Search_Query_Phrase(
                array('word1', 'word2'), array(0,1), 'annotation');

A phrase query can be constructed in one step with a class constructor or step by step with Zend_Search_Lucene_Search_Query_Phrase::addTerm() method calls.

Zend_Search_Lucene_Search_Query_Phrase class constructor takes three optional arguments:

Zend_Search_Lucene_Search_Query_Phrase(
    [array $terms[, array $offsets[, string $field]]]
);

The $terms parameter is an array of strings that contains a set of phrase terms. If it's omitted or equal to null, then an empty query is constructed.

The $offsets parameter is an array of integers that contains offsets of terms in a phrase. If it's omitted or equal to null, then the terms' positions are assumed to be sequential with no gaps.

The $field parameter is a string that indicates the document field to search. If it's omitted or equal to null, then the default field is searched.

Thus:

$query =
    new Zend_Search_Lucene_Search_Query_Phrase(array('zend', 'framework'));

will search for the phrase 'zend framework' in all fields.

$query = new Zend_Search_Lucene_Search_Query_Phrase(
                 array('zend', 'download'), array(0, 2)
             );

will search for the phrase 'zend ????? download' and match 'zend platform download', 'zend studio download', 'zend core download', 'zend framework download', and so on.

$query = new Zend_Search_Lucene_Search_Query_Phrase(
                 array('zend', 'framework'), null, 'title'
             );

will search for the phrase 'zend framework' in the 'title' field.

Zend_Search_Lucene_Search_Query_Phrase::addTerm() takes two arguments, a required Zend_Search_Lucene_Index_Term object and an optional position:

Zend_Search_Lucene_Search_Query_Phrase::addTerm(
    Zend_Search_Lucene_Index_Term $term[, integer $position]
);

The $term parameter describes the next term in the phrase. It must indicate the same field as previous terms, or an exception will be thrown.

The $position parameter indicates the term position in the phrase.

Thus:

$query = new Zend_Search_Lucene_Search_Query_Phrase();
$query->addTerm(new Zend_Search_Lucene_Index_Term('zend'));
$query->addTerm(new Zend_Search_Lucene_Index_Term('framework'));

will search for the phrase 'zend framework'.

$query = new Zend_Search_Lucene_Search_Query_Phrase();
$query->addTerm(new Zend_Search_Lucene_Index_Term('zend'), 0);
$query->addTerm(new Zend_Search_Lucene_Index_Term('framework'), 2);

will search for the phrase 'zend ????? download' and match 'zend platform download', 'zend studio download', 'zend core download', 'zend framework download', and so on.

$query = new Zend_Search_Lucene_Search_Query_Phrase();
$query->addTerm(new Zend_Search_Lucene_Index_Term('zend', 'title'));
$query->addTerm(new Zend_Search_Lucene_Index_Term('framework', 'title'));

will search for the phrase 'zend framework' in the 'title' field.

The slop factor sets the number of other words permitted between specified words in the query phrase. If set to zero, then the corresponding query is an exact phrase search. For larger values this works like the WITHIN or NEAR operators.

The slop factor is in fact an edit distance, where the edits correspond to moving terms in the query phrase. For example, to switch the order of two words requires two moves (the first move places the words atop one another), so to permit re-orderings of phrases, the slop factor must be at least two.

More exact matches are scored higher than sloppier matches; thus, search results are sorted by exactness. The slop is zero by default, requiring exact matches.

The slop factor can be assigned after query creation:

// Query without a gap.
$query =
    new Zend_Search_Lucene_Search_Query_Phrase(array('word1', 'word2'));

// Search for 'word1 word2', 'word1 ... word2'
$query->setSlop(1);
$hits1 = $index->find($query);

// Search for 'word1 word2', 'word1 ... word2',
// 'word1 ... ... word2', 'word2 word1'
$query->setSlop(2);
$hits2 = $index->find($query);

Range Query

Range queries are intended for searching terms within specified interval.

Query string:

mod_date:[20020101 TO 20030101]
title:{Aida TO Carmen}

or

Query construction by API:

$from = new Zend_Search_Lucene_Index_Term('20020101', 'mod_date');
$to   = new Zend_Search_Lucene_Index_Term('20030101', 'mod_date');
$query = new Zend_Search_Lucene_Search_Query_Range(
                 $from, $to, true // inclusive
             );
$hits  = $index->find($query);

Term fields are optional. Zend_Search_Lucene searches through all fields if the field is not specified:

$from = new Zend_Search_Lucene_Index_Term('Aida');
$to   = new Zend_Search_Lucene_Index_Term('Carmen');
$query = new Zend_Search_Lucene_Search_Query_Range(
                 $from, $to, false // non-inclusive
             );
$hits  = $index->find($query);

Either (but not both) of the boundary terms may be set to null. Zend_Search_Lucene searches from the beginning or up to the end of the dictionary for the specified field(s) in this case:

// searches for ['20020101' TO ...]
$from = new Zend_Search_Lucene_Index_Term('20020101', 'mod_date');
$query = new Zend_Search_Lucene_Search_Query_Range(
                 $from, null, true // inclusive
             );
$hits  = $index->find($query);

Previous Next
Introduction to Zend Framework
Présentation
Installation
Zend_Acl
Introduction
Affiner les Contrôles d'Accès
Utilisation avancée
Zend_Amf
Introduction
Zend_Amf_Server
Zend_Auth
Introduction
Authentification avec une table de base de données
Authentification "Digest"
Adaptateur d'authentification HTTP
LDAP Authentication
Authentification OpenID
Zend_Cache
Introduction
Aspect théorique
Les frontends Zend_Cache
Les backends Zend_Cache
Zend_Captcha
Introduction
Opération Captcha
Adaptateurs Captcha
Zend_Config
Introduction
Aspect théorique
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction à Getopt
Déclarer les règles Getopt
Extraire les options et les arguments
Configurer Zend_Console_Getopt
Zend_Controller
Zend_Controller - Démarrage rapide
Fondations de Zend_Controller
Le contrôleur frontal (Front Controller)
L'objet Requête
Routeur Standard
Le dispatcheur
Contrôleurs d'action
Aides d'action (Helper)
Objet de réponse
Plugins
Utilisation de conventions de dossiers modulaires
Exceptions avec MVC
Migrer depuis des versions précédentes
Zend_Currency
Introduction à Zend_Currency
How to work with currencies
Migrer depuis des versions antérieures
Zend_Date
Introduction
Aspect théorique
Méthodes de base
Zend_Date API Overview
Créer des dates
Constants for General Date Functions
Exemples concrets
Zend_Db
Zend_Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
Relations Zend_Db_Table
Zend_Debug
Afficher des informations
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Les aides de vues Dojo
Les éléments de formulaire et les décorateurs Dojo
Zend_Dom
Introduction
Zend_Dom_Query
Zend_Exception
Utiliser les exceptions
Zend_Feed
Introduction
Importer des flux
Obtenir des flux à partir de pages Web
Consommer un flux RSS
Consommer un flux Atom
Consommer une entrée Atom particulière
Modifier la structure du flux ou des entrées
Classes personnalisées pour les flux et entrées
Zend_File
Zend_File_Transfer
Validateurs pour Zend_File_Transfer
Filtres pour Zend_File_Transfer
Migrer à partir des versions précédentes
Zend_Filter
Introduction
Classes de filtre standards
Chaînes de filtrage
Écriture de filtres
Zend_Filter_Input
Zend_Filter_Inflector
Zend_Form
Zend_Form
Zend_Form Quick Start
Creating Form Elements Using Zend_Form_Element
Creating Forms Using Zend_Form
Creating Custom Form Markup Using Zend_Form_Decorator
Standard Form Elements Shipped With Zend Framework
Standard Form Decorators Shipped With Zend Framework
Internationalization of Zend_Form
Advanced Zend_Form Usage
Zend_Gdata
Introduction to Gdata
Authentification par procédé AuthSub
Using the Book Search Data API
Authentification avec ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Health
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Utilisation des albums Web Picasa
Using the YouTube Data API
Attraper les exceptions Gdata
Zend_Http
Zend_Http_Client - Introduction
Zend_Http_Client - Utilisation avancée
Zend_Http_Client - Adaptateurs de connexion
Zend_Http_Cookie and Zend_Http_CookieJar
Zend_Http_Response
Zend_InfoCard
Introduction
Zend_Json
Introduction
Utilisation de base
Objets JSON
XML to JSON conversion
Zend_Json_Server - JSON-RPC server
Zend_Layout
Introduction
Zend_Layout - Démarrage rapide
Zend_Layout options de configuration
Zend_Layout, utilisation avancée
Zend_Ldap
Introduction
Zend_Loader
Charger les fichiers et les classes dynamiquement
Chargeur de Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported locales
Migrer à partir des versions précédentes
Zend_Log
Présentation
Rédacteurs (Writers)
Formateurs (mise en forme)
Filtres
Zend_Mail
Introduction
Envoyer des émail en utilisant SMTP
Envoyer plusieurs émail par connexion SMTP
Utiliser différents transports
Émail HTML
Fichiers joints
Ajouter des destinataires
Contrôler les limites MIME
Entêtes additionnelles
Jeux de caractères
Encodage
Authentification SMTP
Sécuriser les transports SMTP
Lire des émail
Zend_Measure
Introduction
Création d'une mesure
Récupérer des mesures
Manipuler des mesures
Types de mesures
Zend_Memory
Présentation
Manager de mémoire
Objet mémoire
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introduction
Utilisation
Configuration
Utilisation avancée
Zend_Pdf
Introduction.
Créer et charger des documents PDF
Sauvegarder les changement dans un document PDF
Les pages d'un document
Dessiner
Informations du document et métadonnées.
Exemple d'utilisation du module Zend_Pdf
Zend_ProgressBar
Zend_ProgressBar
Zend_Registry
Utiliser le registre
Zend_Rest
Introduction
Zend_Rest_Client
Zend_Rest_Server
Zend_Search_Lucene
Overview
Building Indexes
Searching an Index
Query Language
Query Construction API
Jeu de caractères
Extensibility
Agir avec Lucene Java
Avancé
Best Practices
Zend_Server
Introduction
Zend_Server_Reflection
Zend_Service
Introduction
Zend_Service_Akismet
Zend_Service_Amazon
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_Flickr
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_Simpy
Introduction
Zend_Service_StrikeIron
Zend_Service_StrikeIron: Bundled Services
Zend_Service_StrikeIron: Advanced Uses
Zend_Service_Technorati
Zend_Service_Twitter
Zend_Service_Yahoo
Zend_Session
Introduction
Usage basique
Utilisation avancée
Gestion générale de la session
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL
Auto découverte
Zend_Test
Introduction
Zend_Test_PHPUnit
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Utiliser Zend_TimeSync
Zend_Translate
Introduction
Adaptateurs pour Zend_Translate
Utiliser les adaptateurs de traduction
Migrer à partir des versions précédentes
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Classes de validation standard
Chaînes de validation
Écrire des validateurs
Zend_Version
Lire la version du Zend Framework
Zend_View
Introduction
Scripts de contrôleur
Scripts de vue
Aides de vue
Zend_View_Abstract
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
Configuration système requise par le Zend Framework
Version de PHP requise
Extensions PHP
Les composants du Zend Framework
Dépendances internes du Zend Framework
Convention de codage PHP du Zend Framework
Vue d'ensemble
Formatage des fichiers PHP
Conventions de nommage
Style de codage
Zend Framework Performance Guide
Introduction
Class Loading
Internationalisation (i18n) and Localisation (l10n)
View Rendering
Informations de copyright