Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
La classe Index représente un index permettant d'indexer, de supprimer et de rechercher des documents.
La classe Index est définie dans le module google.appengine.api.search.
Présentation
La classe Index fournit des arguments pour construire un index, ainsi que des fonctions vous permettant d'ajouter, de répertorier, de rechercher et de supprimer des documents (ou une collection de documents itérable) au sein de l'index. Vous construisez un index à l'aide d'arguments de la classe Index, y compris le nom et l'espace de noms de l'index.
Le code suivant montre comment insérer des documents dans un index, puis rechercher des documents correspondant à une requête :
# Get the index.index=search.Index(name='index-name')# Create a document.doc=search.Document(doc_id='document-id',fields=[search.TextField(name='subject',value='my first email'),search.HtmlField(name='body',value='<html>some content here</html>')])# Index the document.try:index.put(doc)exceptsearch.PutError,e:result=e.results[0]ifresult.code==search.OperationResult.TRANSIENT_ERROR:# possibly retry indexing result.object_idexceptsearch.Error,e:# possibly log the failure# Query the index.try:results=index.search('subject:first body:here')# Iterate through the search results.forscored_documentinresults:# process the scored_documentexceptsearch.Error,e:# possibly log the failure
Constructeur
Le constructeur de la classe Index est défini comme suit :
Index(name, namespace=None)
Permet de construire une instance de la classe Index.
Arguments
name
Nom de l'index (voir la section Propriétés ci-dessous pour plus d'informations).
Une instance de la classe Index possède les propriétés suivantes :
schema
Noms de champs de mise en correspondance de schéma associés à la liste des types compatibles. Valide uniquement pour les index renvoyés via la méthode search.get_indexes.
name
Nom d'index, chaîne ASCII lisible destinée à identifier l'index. Ne doit contenir aucun caractère d'espacement ni commencer par un point d'exclamation (!).
namespace
Espace de noms dans lequel le nom d'index est défini.
storage_usage
Nombre approximatif d'octets utilisés par cet index. Peut ne pas refléter les résultats des modifications récentes. Valide uniquement pour les index renvoyés via la méthode search.get_indexes.
storage_limit
Stockage maximal autorisé pour cet index, en octets. Valide uniquement pour les index renvoyés via la méthode search.get_indexes.
Méthodes des instances
Les instances de la classe Index utilisent les méthodes suivantes :
put(self, documents, deadline=None)
Si les documents spécifiés ont déjà été insérés dans l'index et s'ils ont les mêmes valeurs doc_ids, ils sont réindexés avec le contenu mis à jour.
Arguments
documents
Document (ou collection de documents pouvant être remplacés) à indexer.
deadline
Date limite pour l'appel RPC en secondes.
Valeur de résultat
Liste des résultats (PutResult), un pour chaque document devant être indexé.
Exceptions
PutError
Un ou plusieurs documents n'ont pas pu être indexés, ou le numéro indexé ne correspond pas au numéro demandé.
TypeError
Attribut inconnu transmis.
ValueError
Argument (et non un document ou une collection de documents pouvant être remplacés) ou nombre de documents supérieur à MAXIMUM_DOCUMENTS_PER_PUT_REQUEST.
delete(self, document_ids, deadline=None)
Supprime des documents d'un index.
S'il n'existe aucun document associé à un identifiant dans la liste, cet identifiant est ignoré.
Arguments
document_ids
Identifiant (ou liste d'identifiants) des documents à supprimer.
deadline
Date limite pour l'appel RPC en secondes.
Exceptions
DeleteError
Un ou plusieurs documents n'ont pas pu être supprimés, ou le numéro supprimé ne correspond pas au numéro demandé.
ValueError
Argument (et non une chaîne ou une collection d'identifiants de document valides pouvant être remplacés) ou nombre d'identifiants de document supérieur à MAXIMUM_DOCUMENTS_PER_PUT_REQUEST.
get(self,doc_id, deadline=None)
Récupère un document de l'index en utilisant l'identifiant du document. Si le document n'est pas trouvé, la valeur None est renvoyée.
Arguments
doc_id
Identifiant du document à récupérer.
deadline
Date limite pour l'appel RPC en secondes.
Valeur de résultat
Objet Document dont l'identifiant correspond à celui fourni par doc_id.
search(query, deadline=None)
Recherche dans l'index les documents correspondant à la requête. La requête peut être une chaîne ou un objet Query.
Par exemple, le fragment de code ci-après demande une recherche de documents à partir du terme "first" dans le sujet et du terme "good" présent partout dans le texte, selon les critères suivants : renvoi de 20 documents au plus, curseur de résultats sur un seul document, tri par sujet et par ordre décroissant, et champs d'auteur, de sujet, de résumé et d'extrait de contenu.
results=index.search(# Define the query by using a Query object.query=Query('subject:first good',options=QueryOptions(limit=20,cursor=Cursor(),sort_options=SortOptions(expressions=[SortExpression(expression='subject',default_value='')],limit=1000),returned_fields=['author','subject','summary'],snippeted_fields=['content'])))
Le fragment de code suivant montre comment utiliser un curseur de résultats.
cursor=results.cursorforresultinresults:# process resultresults=index.search(Query('subject:first good',options=QueryOptions(cursor=cursor)))
Le fragment de code suivant montre comment utiliser un curseur per_result :
Requête à faire correspondre aux documents de l'index, décrite dans un objet Query. Pour plus d'informations, consultez la présentation du langage de requête.
deadline
Date limite pour l'appel RPC en secondes.
Valeur de résultat
Objet SearchResults contenant une liste de documents correspondants, le nombre renvoyé et le nombre correspondant à la requête.
Exceptions
TypeError
L'un des paramètres possède un type non valide ou un attribut inconnu a été transmis.
ValueError
L'un des paramètres contient une valeur non valide.
Obtient une plage de documents à partir d'un index, classés selon l'identifiant de document (doc_id).
Arguments
start_id
Chaîne contenant l'identifiant du document à partir duquel répertorier les documents. Par défaut, commence par le premier identifiant de document.
include_start_object
Si la valeur est définie sur true, inclut le document spécifié par start_id.
limit
Nombre maximal de documents à renvoyer.
ids_only
Si la valeur est définie sur true, renvoie uniquement les identifiants de document au lieu de documents complets.
deadline
Date limite pour l'appel RPC en secondes.
Valeur de résultat
Objet A GetResponse contenant une liste des documents récupérés, classés selon l'identifiant de document.
Exceptions
TypeError
Attribut inconnu transmis.
Erreur
Une sous-classe d'erreur (Error) est survenue lors du traitement de la demande.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/04 (UTC)."],[[["\u003cp\u003eThe \u003ccode\u003eIndex\u003c/code\u003e class allows for the management of documents within an index, including indexing, deleting, and searching.\u003c/p\u003e\n"],["\u003cp\u003eAsynchronous methods like \u003ccode\u003eput_async\u003c/code\u003e, \u003ccode\u003edelete_async\u003c/code\u003e, \u003ccode\u003eget_async\u003c/code\u003e, \u003ccode\u003esearch_async\u003c/code\u003e, and \u003ccode\u003eget_range_async\u003c/code\u003e are available, returning a future object that can be used to retrieve the result via \u003ccode\u003eget_result()\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eIndex\u003c/code\u003e constructor takes the index's \u003ccode\u003ename\u003c/code\u003e and an optional \u003ccode\u003enamespace\u003c/code\u003e to create an instance, which can be used to perform methods like \u003ccode\u003eput\u003c/code\u003e, \u003ccode\u003edelete\u003c/code\u003e, \u003ccode\u003eget\u003c/code\u003e, \u003ccode\u003esearch\u003c/code\u003e, and \u003ccode\u003eget_range\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003esearch\u003c/code\u003e method allows querying the index using a string or a \u003ccode\u003eQuery\u003c/code\u003e object, which can be further customized with a \u003ccode\u003eQueryOptions\u003c/code\u003e to control parameters like limits, cursors, and sort options.\u003c/p\u003e\n"],["\u003cp\u003eThe properties of an \u003ccode\u003eIndex\u003c/code\u003e object include the name, namespace, schema, storage_usage, and storage_limit, while instance methods allow to manage documents, like put a document to the index, deleting an existing one, retrieving a document by it's ID, searching for documents matching a query and retrieving a range of documents by ID.\u003c/p\u003e\n"]]],[],null,["# The Index Class\n\nClass `Index` represents an index allowing documents to be indexed, deleted, and searched.\n| This API is supported for first-generation runtimes and can be used when [upgrading to corresponding second-generation runtimes](/appengine/docs/standard/\n| python3\n|\n| /services/access). If you are updating to the App Engine Python 3 runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/python-differences) to learn about your migration options for legacy bundled services.\n\n`Index` is defined in the `google.appengine.api.search` module.\n| **Note:** There are asynchronous methods corresponding to each instance method: `put_async`, `delete_async`, `get_async`, `search_async`, and `get_range_async`. These are identical to the synchronous methods, except they all return a future. To get the actual result, call `get_result()` on the returned value; that call will block.\n\nIntroduction\n------------\n\nThe `Index` class provides arguments to construct an index as well as functions allowing you to add, list, search, and delete [documents](/appengine/docs/legacy/standard/python/search/documentclass) (or an iterable collection of documents) within the index. You construct an index using arguments to the `Index` class, including the name and namespace of the index.\n\nThe following code shows how to put documents into an index, then search it for documents matching a query: \n\n```python\n# Get the index.\nindex = search.Index(name='index-name')\n\n# Create a document.\ndoc = search.Document(\n doc_id='document-id',\n fields=[search.TextField(name='subject', value='my first email'),\n search.HtmlField(name='body', value='\u003chtml\u003esome content here\u003c/html\u003e')])\n\n# Index the document.\ntry:\n index.put(doc)\nexcept search.PutError, e:\n result = e.results[0]\n if result.code == search.OperationResult.TRANSIENT_ERROR:\n # possibly retry indexing result.object_id\nexcept search.Error, e:\n # possibly log the failure\n\n# Query the index.\ntry:\n results = index.search('subject:first body:here')\n\n # Iterate through the search results.\n for scored_document in results:\n # process the scored_document\n\nexcept search.Error, e:\n # possibly log the failure\n```\n\nConstructor\n-----------\n\nThe constructor for class `Index` is defined as follows:\n\n\nIndex(name, namespace=None)\n\n: Construct an instance of class `Index`.\n\n: Arguments\n\n name\n\n : Index name (see [name property](#Index_name), below, for details).\n\n namespace\n\n : For [multitenant applications](/appengine/docs/legacy/standard/python/multitenancy), the namespace in which index name is defined.\n\n Result value\n\n : A new instance of class `Index`.\n\n \u003cbr /\u003e\n\nProperties\n----------\n\nAn instance of class `Index` has the following properties:\n\nschema\n\n: Schema mapping field names to the list of types supported. Valid only\n for indexes returned by the [search.get_indexes](/appengine/docs/legacy/standard/python/search/functions#get_indexes)\n method.\n\nname\n\n: Index name, a human-readable ASCII string identifying the index. Must contain no whitespace characters and not start with an exclamation point (`!`).\n\nnamespace\n\n: Namespace in which index name is defined.\n\nstorage_usage\n\n: The approximate number of bytes used by this index. The number may not reflect the\n results of recent changes. Valid only\n for indexes returned by the [search.get_indexes](/appengine/docs/legacy/standard/python/search/functions#get_indexes)\n method.\n\nstorage_limit\n\n: The maximum allowable storage for this index, in bytes. Valid only\n for indexes returned by the [search.get_indexes](/appengine/docs/legacy/standard/python/search/functions#get_indexes)\n method.\n\nInstance Methods\n----------------\n\nInstances of class `Index` have the following methods:\n\nput(self, documents, deadline=None)\n\n: If the specified documents have already been put into the index, and if they have the same `doc_ids`, they are reindexed with updated contents.\n\n: Arguments\n\n documents\n\n : Document (or iterable collection of documents) to index.\n\n deadline\n\n : Deadline for RPC call in seconds.\n\n Result value\n\n : List of results (`PutResult`), one for each document requested to be indexed.\n\n Exceptions\n\n PutError\n\n : One or more documents failed to index, or number indexed did not match number requested.\n\n TypeError\n\n : Unknown attribute passed.\n\n ValueError\n\n : Argument not a document or iterable collection of documents, or number of documents larger than `MAXIMUM_DOCUMENTS_PER_PUT_REQUEST`.\n\n\ndelete(self, document_ids, deadline=None)\n\n: Delete documents from index.\n\n If no document exists for an identifier in the list, that identifier is ignored.\n\n: Arguments\n\n document_ids\n\n : Identifier (or list of identifiers) of documents to delete.\n\n deadline\n\n : Deadline for RPC call in seconds.\n\n Exceptions\n\n DeleteError\n\n : One or more documents failed to delete, or number deleted did not match number requested.\n\n ValueError\n\n : Argument not a string or iterable collection of valid document identifiers, or number of document identifiers larger than `MAXIMUM_DOCUMENTS_PER_PUT_REQUEST`.\n\n\nget(self,doc_id, deadline=None)\n\n: Retrieves a [Document](/appengine/docs/legacy/standard/python/search/documentclass) from the index using the document's identifier. If the document is not found, returns `None`.\n\n: Arguments\n\n doc_id\n\n : The identifier of the document to retrieve.\n\n deadline\n\n : Deadline for RPC call in seconds.\n\n Result value\n\n : A [Document](/appengine/docs/legacy/standard/python/search/documentclass) object whose identifier matches the one supplied by doc_id.\n\n\nsearch(query, deadline=None)\n\n: Search the index for documents matching the query. The query may be either a string or a [Query](/appengine/docs/legacy/standard/python/search/queryclass) object.\n\n For example, the following code fragment requests a search for documents where 'first' occurs in subject and 'good' occurs anywhere, returning at most 20 documents, starting the search from 'cursor token', returning another single cursor for the response, sorting by subject in descending order, returning the author, subject, and summary fields as well as a snippeted field content. \n\n ```python\n results = index.search(\n # Define the query by using a Query object.\n query=Query('subject:first good',\n options=QueryOptions(limit=20,\n cursor=Cursor(),\n sort_options=SortOptions(\n expressions=[SortExpression(expression='subject',\n default_value='')],\n limit=1000),\n returned_fields=['author', 'subject', 'summary'],\n snippeted_fields=['content'])))\n ```\n\n The following code fragment shows how to use a results cursor. \n\n ```python\n cursor = results.cursor\n for result in results:\n # process result\n results = index.search(Query('subject:first good',\n options=QueryOptions(cursor=cursor))\n )\n ```\n\n The following code fragment shows how to use a `per_result` cursor: \n\n ```python\n results = index.search(query=Query('subject:first good',\n options=QueryOptions(limit=20,\n cursor=Cursor(per_result=True),\n ...))\n )\n\n cursor = None\n for result in results:\n cursor = result.cursor\n\n results = index.search(\n Query('subject:first good', options=QueryOptions(cursor=cursor))\n )\n ```\n\n: Arguments\n\n query\n\n : The query to match against documents in the index, described in a [Query](/appengine/docs/legacy/standard/python/search/queryclass) object. For more information, please see the [Query Language Overview](/appengine/docs/legacy/standard/python/search#Query_Language_Overview).\n\n deadline\n\n : Deadline for RPC call in seconds.\n\n Result value\n\n : A [SearchResults](/appengine/docs/legacy/standard/python/search/searchresultsclass) object containing a list of documents matched, number returned and number matched by the query.\n\n Exceptions\n\n TypeError\n\n : A parameter has an invalid type, or an unknown attribute was passed.\n\n ValueError\n\n : A parameter has an invalid value.\n\n\nget_range(self, start_id=None, include_start_object=True, limit=100, ids_only=False, deadline=None)\n\n: Get a range of documents from an index, in `doc_id` order.\n\n: Arguments\n\n start_id\n\n : String containing the document identifier from which to list documents. By default, starts at the first document identifier.\n\n include_start_object\n\n : If `true`, include document specified by `start_id`.\n\n limit\n\n : Maximum number of documents to return.\n\n ids_only\n\n : If `true`, return only document identifiers instead of full documents.\n\n deadline\n\n : Deadline for RPC call in seconds.\n\n Result value\n\n : `A `[GetResponse](/appengine/docs/legacy/standard/python/search/getresponseclass) object containing a list of the retrieved documents, ordered by document identifier.\n\n Exceptions\n\n TypeError\n\n : Unknown attribute passed.\n\n Error\n\n : Some subclass of `Error` occurred while processing request."]]