Changes in trunk/workshop-foss4g/indexing.rst [47:1]
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/workshop-foss4g/indexing.rst
r47 r1 1 1 .. _indexing: 2 2 3 Partie 14 : L'indexation spatiale 4 ============================ =====3 Section 14: Spatial Indexing 4 ============================ 5 5 6 R apellez-vous que l'indexation spatiale est l'une des trois fonctionnalités clés d'une base de données spatiales. Les indexes permettent l'utilisation de grandes quantités de données dans une base. Sans l'indexation, chaque recherche d'entité nécessitera d'accéder séquentiellement à tout les enregistrements de la base de données. L'indexation accélÚres les recherche en organisant les données dans des arbres de recherche qui peuvent être parcouru efficacement pour retrouver une entité particuliÚre.6 Recall that spatial index is one of the three key features of a spatial database. Indexes are what make using a spatial database for large data sets possible. Without indexing, any search for a feature would require a âsequential scanâ of every record in the database. Indexing speeds up searching by organizing the data into a search tree which can be quickly traversed to find a particular record. 7 7 8 L'indexation spatiale l'un des plus grands atouts de PostGIS. Dans les exemples précédents, nous avons construit nos jointures spatiales en comparant la totalité des tables. Ceci peut parfois s'averrer trÚs coûteux : Réaliser la jointure de deux tables de 10000 enregistrements sans indexation nécessitera de comparer 100000000 valeurs, les comparaisons requises ne seront plus que 20000 avec l'indexation.8 Spatial indices are one of the greatest assets of PostGIS. In the previous example building spatial joins requires comparing whole tables with each other. This can get very costly: joining two tables of 10,000 records each without indexes would require 100,000,000 comparisons; with indexes the cost could be as low as 20,000 comparisons. 9 9 10 Lorsque nous avons chargé la table ``nyc_census_blocks``, l'outils pgShapeLoader crée automatiquement un indexe spatial appelé ``nyc_census_blocks_the_geom_gist``. 10 When we loaded the ``nyc_census_blocks`` table, the pgShapeLoader automatically created a spatial index called ``nyc_census_blocks_the_geom_gist`` 11 11 12 Pour démontrer combien il est important d'indexer ses données pour la performance des requêtes, essayons de requêter notre table ``nyc_census_blocks`` **sans** utiliser notre indexe. 12 To demonstrate how important indexes are for performance, let's search ``nyc_census_blocks`` **without** our spatial index. 13 13 14 La premiÚre étape consiste à supprimer l'index.14 Our first step is to remove the index. 15 15 16 16 .. code-block:: sql … … 20 20 .. note:: 21 21 22 La commande ``DROP INDEX`` supprime un index existant de la base de données. Pour de plus amples informations à ce sujet, consultez la `documentation officielle de PostgreSQL <http://docs.postgresql.fr/9.1/sql-dropindex.html>`_.22 The ``DROP INDEX`` statement drops an existing index from the database system. For more information, see the PostgreSQL `documentation <http://www.postgresql.org/docs/7.4/interactive/sql-dropindex.html>`_. 23 23 24 Maintenant, regardons le temps d'exécution dans le coin en bas à droite de l'interface de requêtage de pgAdmin, puis lançons la commande suivante. Notre requête recherche les blocs de la rue Broad.24 Now, watch the "Timing" meter at the lower right-hand corner of the pgAdmin query window and run the following. Our query searches through every single census block in order to identify the Broad Street entry. 25 25 26 26 .. code-block:: sql … … 38 38 360610007003006 39 39 40 La table ``nyc_census_blocks`` est trÚs petite (seulement quelque millier d'enregistrements) donc même sans l'index, la requête prends **55 ms** sur l'ordinateur de test.40 The ``nyc_census_blocks`` table is very small (only a few thousand records) so even without an index, the query only takes **55 ms** on my test computer. 41 41 42 Maintenant remettons en place l'index et lançons de nouveau la requête. 42 Now add the spatial index back in and run the query again. 43 43 44 44 .. code-block:: sql … … 46 46 CREATE INDEX nyc_census_blocks_the_geom_gist ON nyc_census_blocks USING GIST (the_geom); 47 47 48 .. note:: l'utilisation de la clause ``USING GIST`` spécifie à PostgreSQL de créer une structure (GIST) pour cet index. Si vous recevez un message d'erreur ressemblant à ``ERROR: index row requires 11340 bytes, maximum size is 8191`` lors de la création, cela signifie sans doute que vous avez omis la clause ``USING GIST``.48 .. note:: The ``USING GIST`` clause tells PostgreSQL to use the generic index structure (GIST) when building the index. If you receive an error that looks like ``ERROR: index row requires 11340 bytes, maximum size is 8191`` when creating your index, you have likely neglected to add the ``USING GIST`` clause. 49 49 50 Sur l'rdinateur de test le temps d'exécution se réduit à **9 ms**. Plus votre table est grande, plus la différence de temps d'exécution pour une requête utilisant les indexes augmentera.50 On my test computer the time drops to **9 ms**. The larger your table, the larger the relative speed improvement of an indexed query will be. 51 51 52 Comment les indexes spatiaux fonctionnent 53 ------------------------ -----------------52 How Spatial Indexes Work 53 ------------------------ 54 54 55 Les indexes des base de données standards créent des arbres hierarchiques basés sur les valeurs des colonnes à indexer. Les indexes spatiaux sont un peu différents - ils ne sont pas capables d'indexer des entités géométriques elles-même mais indexe leur étendues.55 Standard database indexes create a hierarchical tree based on the values of the column being indexed. Spatial indexes are a little different -- they are unable to index the geometric features themselves and instead index the bounding boxes of the features. 56 56 57 57 .. image:: ./indexing/bbox.png 58 58 59 Dans la figure ci-dessus, le nombre de lignes qui intersectent l'étoile jaune est *unique*, la ligne rouge. Mais l'étendue des entités qui intersectent la boîte jaune sont *deux*, la boîte rouge et la boîte bleue. 59 In the figure above, the number of lines that intersect the yellow star is **one**, the red line. But the bounding boxes of features that intersect the yellow box is **two**, the red and blue ones. 60 60 61 La maniÚre dont les bases de données répondent de maniÚre efficace à la question "Quelles lignes intersectent l'étoile jaune ?" correspond premiÚrement à répondre à la question "Quelle étendue intersecte l'étendue jaune" en utilisant les indexes (ce qui est trÚs rapide) puis à calculer le résultat exact de la question "Quelles lignes intersectent l'étoile jaune ?" **seulement en utilisant les entités retourné par le premier test**. 61 The way the database efficiently answers the question "what lines intersect the yellow star" is to first answer the question "what boxes intersect the yellow box" using the index (which is very fast) and then do an exact calculation of "what lines intersect the yellow star" **only for those features returned by the first test**. 62 62 63 Pour de grandes tables, il y a un systÚme en "deux étapes" d'évaluation en utilisant dans un premier temps l'approximation à l'aide d'indexes, puis en réalisant le test exact sur une quantité bien moins importante de données ce qui réduit drastiquement le temps de calcul nécessaire à cette deuxiÚme étape.63 For a large table, this "two pass" system of evaluating the approximate index first, then carrying out an exact test can radically reduce the amount of calculations necessary to answer a query. 64 64 65 PotGIS et Oracle Spatial partage la même notion d'index structuré sous la forme "d'arbres R" [#RTree]_. Les arbres R classent les données sous forme de rectangles, de sous-rectangles etc. Cette structure d'index gÚre automatiquement la densité et la taille des objets.65 Both PostGIS and Oracle Spatial share the same "R-Tree" [#RTree]_ spatial index structure. R-Trees break up data into rectangles, and sub-rectangles, and sub-sub rectangles, etc. It is a self-tuning index structure that automatically handles variable data density and object size. 66 66 67 67 .. image:: ./indexing/index-01.png 68 68 69 Requête avec seulement des indexes70 ------------------ ----------------69 Index-Only Queries 70 ------------------ 71 71 72 La plupart des fonctions utilisées par PostGIS (:command:`ST_Contains`, :command:`ST_Intersects`, :command:`ST_DWithin`, etc) prennent en compte les indexes automatiquement. Mais certaines fonctions (comme par exemple : :command:`ST_Relate`) ne les utilisent pas.72 Most of the commonly used functions in PostGIS (:command:`ST_Contains`, :command:`ST_Intersects`, :command:`ST_DWithin`, etc) include an index filter automatically. But some functions (e.g., :command:`ST_Relate`) do not include and index filter. 73 73 74 Pour utiliser une recherche par étendue utilisant les indexes (et pas de filtres), vous pouvez utiliser l'opérateur :command:`&&`. Pour les géométries, l'opérateur :command:`&&` signifie "l'étendue recouvre ou touche" de la même maniÚre que l'opérateur :command:`=` sur des entiers signifie que les valeurs sont égales.74 To do a bounding-box search using the index (and no filtering), make use of the :command:`&&` operator. For geometries, the :command:`&&` operator means "bounding boxes overlap or touch" in the same way that for number the :command:`=` operator means "values are the same". 75 75 76 Essayons de comparer une requête avec seulement un indexe pour la population du quartier 'West Village'. En utilisant la commande :command:`&&` notre requête ressemble à cela:76 Let's compare an index-only query for the population of the 'West Village' to a more exact query. Using :command:`&&` our index-only query looks like the following: 77 77 78 78 .. code-block:: sql … … 88 88 50325 89 89 90 Maintenant essayons la même requête en utilisant la fonction plus précise :command:`ST_Intersects`.90 Now let's do the same query using the more exact :command:`ST_Intersects` function. 91 91 92 92 .. code-block:: sql … … 102 102 27141 103 103 104 Un plus faible nombre de résultats ! La premiÚre requête nous renvoit tout les blocs qui intersectent l'étendue du quartier, la seconde nous renvoit seulement les blocs qui intersectent le quartier lui-même.104 A much lower answer! The first query summed up every block that intersected the neighborhood's bounding box; the second query only summed up those blocks that intersected the neighborhood itself. 105 105 106 Analy se106 Analyzing 107 107 --------- 108 108 109 Le plannificateur de requête de PostgreSQL choisit intelligemment d'utiliser ou non les indexes pour réaliser une requête. Il n'est pas toujours plus rapide d'utiliser un index pour réaliser une recherche : si la recherche doit renvoyer l'ensemble des enregistrements d'une table, parcourir l'index pour récupérer chaque valeur sera plus lent que de parcourir linéairement l'ensemble de la table.109 The PostgreSQL query planner intelligently chooses when to use or not to use indexes to evaluate a query. Counter-intuitively, it is not always faster to do an index search: if the search is going to return every record in the table, traversing the index tree to get each record will actually be slower than just linearly reading the whole table from the start. 110 110 111 Afin de savoir dans quelle situation il est nécessaire d'utiliser les idexes (lire une petite partie de la table plutÃŽt qu'une grande partie), PostgreSQL conserve des statistiques relatives à la distribution des données dans chaque colonne indexée. Par défaut, PostgreSQL rassemble les statistiques sur une base réguliÚre. Nénamoins, si vous changez dramatiquement le contenu de vos tables dans une période courte, les statisuqes ne seront alors plus à jour.111 In order to figure out what situation it is dealing with (reading a small part of the table versus reading a large portion of the table), PostgreSQL keeps statistics about the distribution of data in each indexed table column. By default, PostgreSQL gathers statistics on a regular basis. However, if you dramatically change the make-up of your table within a short period of time, the statistics will not be up-to-date. 112 112 113 Pour vous assurez que les statistiques correspondent bien au contenu de la table actuelle, il est courrant d'utiliser la commande ``ANALYZE`` aprÚs un grand nombre de modifications ou de suppression de vos données. Cela force le systÚme de gestion des statistiques à récupérer l'ensemble des données des colonnes indexées.113 To ensure your statistics match your table contents, it is wise the to run the ``ANALYZE`` command after bulk data loads and deletes in your tables. This force the statistics system to gather data for all your indexed columns. 114 114 115 La commande ``ANALYZE`` demande à PostgreSQL de parcourir la table et de mettre à jour les statistiques utilisées par le plannificateur de requêtes (la plannification des requêtes sera traité utiltérieurement). 115 The ``ANALYZE`` command asks PostgreSQL to traverse the table and update its internal statistics used for query plan estimation (query plan analysis will be discussed later). 116 116 117 117 .. code-block:: sql … … 119 119 ANALYZE nyc_census_blocks; 120 120 121 Néttoyage 121 Vacuuming 122 122 --------- 123 123 124 I l est souvent stressant de constater que la simple création d'un indexe n'est pas suffisant pour que PostgreSQL l'utilise efficacement. Le nettoyage doit être réalisé aprÚs qu'un indexe soit créé ou aprÚs un grand nombre de requêtes UDATE, INSERT ou DELETE est été réalisé sur une table. La commande ``VACUUM`` demande à PostgreSQL de récupérer chaque espace non utilisé dans les pages de la table qui sont laissé en l'état lors des requêtes UPDATE ou DELETE à cause du modÚle d'estapillage multi-versions.124 It's worth stressing that just creating an index is not enough to allow PostgreSQL to use it effectively. VACUUMing must be performed whenever a new index is created or after a large number of UPDATEs, INSERTs or DELETEs are issued against a table. The ``VACUUM`` command asks PostgreSQL to reclaim any unused space in the table pages left by updates or deletes to records. 125 125 126 Le nettoyage des données est tellement important pour une utilisation efficace du serveur de base de données PostgreSQL qu'il existe maintenant une option "autovacuum".126 Vacuuming is so critical for the efficient running of the database that PostgreSQL provides an "autovacuum" option. 127 127 128 Activée par défaut, le processus autovacuum nettoie (récupÚre l'espace libre) et analyse (met à jour les statistiques) vos tables suivant un interval donné déterminé par l'activité des bases de données. Bien que cela fonctionne avec les bases de données hautement transactionnelles, il n'est pas supportable de devoir attendre que le processus autovacuum se lance lors de la mise à jour ou la suppression massive de données. Dans ce cas, il faut lancer la commande ``VACUUM`` manuellement.128 Enabled by default, autovacuum both vacuums (recovers space) and analyzes (updates statistics) on your tables at sensible intervals determined by the level of activity. While this is essential for highly transactional databases, it is not advisable to wait for an autovacuum run after adding indices or bulk-loading data. If a large batch update is performed, you should manually run ``VACUUM``. 129 129 130 Le nettoyage et l'analyse de la base de données peut être réalisé séparément si nécessaire. Utiliser la commande ``VACUUM`` ne mettra pas à jour les statistiques alors que lancer la commande ``ANALYZE`` ne récupÚrera pas l'espace libre des lignes d'une table. Chacune de ces commandes peut être lancée sur l'intégralité de la base de données, sur une table ou sur une seule colonne.130 Vacuuming and analyzing the database can be performed separately as needed. Issuing ``VACUUM`` command will not update the database statistics; likewise issuing an ``ANALYZE`` command will not recover unused table rows. Both commands can be run against the entire database, a single table, or a single column. 131 131 132 132 .. code-block:: sql … … 134 134 VACUUM ANALYZE nyc_census_blocks; 135 135 136 Liste des fonctions 137 ------------- ------136 Function List 137 ------------- 138 138 139 `geometry_a && geometry_b <http://postgis.org/docs/ST_Geometry_Overlap.html>`_: retourne TRUE si l'étendue de A cheuvauche celle de B.139 `geometry_a && geometry_b <http://postgis.org/docs/ST_Geometry_Overlap.html>`_: Returns TRUE if A's bounding box overlaps B's. 140 140 141 `geometry_a = geometry_b <http://postgis.org/docs/ST_Geometry_EQ.html>`_: retourne TRUE si l'étendue de A est la même que celle de B.141 `geometry_a = geometry_b <http://postgis.org/docs/ST_Geometry_EQ.html>`_: Returns TRUE if A's bounding box is the same as B's. 142 142 143 `ST_Intersects(geometry_a, geometry_b) <http://postgis.org/docs/ST_Intersects.html>`_: retourne TRUE si l'objet Geometrie/Geography "intersecte spatiallement" - (ont une partie en commun) et FALSE sinon (elles sont dijointes).143 `ST_Intersects(geometry_a, geometry_b) <http://postgis.org/docs/ST_Intersects.html>`_: Returns TRUE if the Geometries/Geography "spatially intersect" - (share any portion of space) and FALSE if they don't (they are Disjoint). 144 144 145 145 .. rubric:: Footnotes
Note: See TracChangeset
for help on using the changeset viewer.