SlideShare a Scribd company logo
1 of 21
Download to read offline
Using PostgreSQL
  In Web 2.0 Applications
       How PostgreSQL helps to build Web 2.0 Apps




                          Nikolay Samokhvalov
                 Postgresmen, LLC (Moscow, Russia)




PostgreSQL Conference East 2008
What Is Web 2.0?




Using PostgreSQL In Web 2.0 Applications
What Is Web 2.0?

     For users:
           Collaborative web (UGC*, comments, rating system, etc)
           Web applications, not web sites (AJAX, more interaction)
           Web as a platform (interoperability, RSS, microformats, etc)
           Rounded corners, mirrored logos etc :­)




      *)
            UGC — user­generated content


Using PostgreSQL In Web 2.0 Applications
What Is Web 2.0?

     For software developers it means:

                             more users        more developers   more brands


                                             more competitors
                                              on the market


       higher                          rapidly                                 number of users,
                                                              larger           pageviews, TPS,
      rates of                        changing
  development,                                                 data                 etc:
                                      business
                                                             volumes
 shorter iterations                 requirements                                   N = et

                                Better technologies help to win!

Using PostgreSQL In Web 2.0 Applications
Why PostgreSQL?

     1. Performance, scalability
     2. Reliability
     3. Powerful capabilities
     4. Standards compliance, proper approaches
     5. Freedom




Using PostgreSQL In Web 2.0 Applications
Why PostgreSQL?

     1. Performance, scalability
     2. Reliability                               }   Quality


     3. Powerful capabilities                     } Development efficiency
     4. Standards compliance, proper approaches
     5. Freedom
                                                  }    HR




Using PostgreSQL In Web 2.0 Applications
How to Deal With UGC?

     1. Taxonomy
           ●   Catalogs
     2. Folksonomy
           ●   Tags
     3. Hybrid, two ways:
           ●   Tags + Catalogs
           ●   Both users and editors control Catalogs




Using PostgreSQL In Web 2.0 Applications
UGC: Taxonomy

     1. Taxonomy (Catalogs)
           ●   EAV, where ATTRIBUTE table is [almost] constant
           ●   intarray / hstore




Using PostgreSQL In Web 2.0 Applications
EAV: Entity­Attibute­Value
   Entity
                                                       Value




                                           Attribute
Using PostgreSQL In Web 2.0 Applications
intarray / hstore
                                                        item

                                           obj_id              INT8
                                           item_section_id     INT8
                                           item_vendor_id      INT8
                                           item_model_id       INT8
                                           item_year           INT2
                                           item_price          NUMERIC(30,6)
                                           item_props          intarray

     What about performance?
     ●   This approach allows to save much space
     ●   Performance is good if you mix GiST/GIN search with FTS search
     ●   Better to cache tag values in external cache (e.g. Memcache) if you use 
         intarray, but in this case using FTS is a bit harder



Using PostgreSQL In Web 2.0 Applications
UGC: Folksonomy

     1. Folksonomy (Tags)
           1. EAV (again), user­controlled ATTRIBUTE table
           2. intarray / hstore (again)


               — it's just almost the same, you just give control to your users

                                           Tags:




Using PostgreSQL In Web 2.0 Applications
UGC: Hybrid

     1. Hybrid, two ways:
           1. Tags + Catalogs
                  —  common practice
           2. Both users and editors control Catalogs
                  —  is the most interesting, but is the most difficult to implement and 
                   maintain 
                  ●   UGC­only catalog entries are not shown in common <SELECT> 
                      lists, they are waiting for editors approval.
                  ●   'Merge' procedure is really complicated (merge UGC with editors' 
                      data; merge duplicates, synonyms, etc).
                  ●   FTS (stemming, morphology, thesaurus), pg_trgm, metaphone, 
                      soundex, etc may help. BUT: human work is still needed.

Using PostgreSQL In Web 2.0 Applications
UGC: More About Tags

     1. Use FTS (tsearch2) to integrate tag searching in your search subsystem:
           ●   use FTS categories to differ tag words from mere words when needed;
           ●   to process tags, use separate FTS configuration, if needed.
     2. Use quot;prefix searchquot; for tag searching, but it's not straightforward (wait for 
        the next slides ;­) )




Using PostgreSQL In Web 2.0 Applications
UGC: Tags And Prefix Search

     quot;Prefix searchquot; helps to build smth like this:




     If you use simple LIKE 'bla%' the result will be somewhat dissapointing:
   test=# EXPLAIN ANALYZE SELECT * FROM tag WHERE tag_name LIKE 'bla%';
                                 QUERY PLAN
   ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
    Seq Scan on tag  (cost=0.00..6182.75 rows=1 width=105) (actual
   time=0.951..102.779 rows=162 loops=1)
      Filter: ((tag_name)::text ~~ 'bla%'::text)
    Total runtime: 102.871 ms
   (3 rows)

   Notice: ~300k unique tags in the table
Using PostgreSQL In Web 2.0 Applications
Tags And Prefix Search:
                               The Proper Solution
     1. Use text_pattern_ops to speed up LIKE 'bla%' queries:
   test=# CREATE INDEX i_tag_prefix ON tag 
               USING btree(lower(tag_name) text_pattern_ops);
   CREATE INDEX

   test=# EXPLAIN ANALYZE SELECT * FROM tag 
               WHERE lower(tag_name) LIKE lower('bla%');
                                QUERY PLAN
   ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
    Bitmap Heap Scan on tag  (cost=43.55..2356.16 rows=1096 width=105)
   (actual time=0.164..0.791 rows=235 loops=1)
      Filter: (lower((tag_name)::text) ~~ 'bla%'::text)
      ­>  Bitmap Index Scan on i_tag_prefix  (cost=0.00..43.28 rows=1096
   width=0) (actual time=0.116..0.116 rows=235 loops=1)
            Index Cond: ((lower((tag_name)::text) ~>=~ 'bla'::text) AND
   (lower((tag_name)::text) ~<~ 'мис'::text))
    Total runtime: 0.885 ms
   (5 rows)

   Notices: (1) ILIKE is not acceptable, so use lower(); (2) be careful using non­ASCII charactes 
   (i.e. it's OK for Russian UTF­8 except minor 'ё' & 'Ё' chars)
Using PostgreSQL In Web 2.0 Applications
Tags And Prefix Search:
                               The Proper Solution
     2. Create tag_words (unique tag words) table to work with words, not with phrases:
   CREATE TABLE tag_words AS 
       SELECT DISTINCT word 
       FROM ts_stat('SELECT to_tsvector(tag_name) FROM tag'); ­­ heavy
   DROP INDEX i_tag_prefix;
   CREATE INDEX i_tag_fts ON tag USING gin(to_tsvector(tag_name));
   CREATE INDEX i_tag_words_prefix ON tag_words 
       USING btree(lower(word) text_pattern_ops);

   test=# EXPLAIN ANALYZE 
     SELECT * FROM tag 
     WHERE to_tsvector('utf8_russian'::regconfig, tag_name::text) 
           @@ to_tsquery('utf8_russian', '(' || (
             SELECT array_to_string(array_accum(lower(word)), '|')
             FROM tag_words
             WHERE lower(word) LIKE 'bla%') || ')'); ­­ add '...&word1&word2' if needed
   /* plan is omitted */
    Total runtime: 13.243 ms
   (11 rows)

   Notices: (1) better to limit number of tag words found by the inner query (e.g. ordering by word 
   age — dirty but it works); (2) word order in original query is lost, unfortunately; (3) GIN indexes 
   are better than GiST here
Using PostgreSQL In Web 2.0 Applications
Rate And Comment Everything
        PostgreSQL Inheritance helps to achieve development efficiency
                                           obj

                    obj_id                          INT8          — Not SERIAL, wait for the next slide to see details
                    obj_status_did                  INT8          — Dictionary value
                    obj_creator_obj_id              INT8          — ID of user who created the record (if applicable)
                    obj_created                     TIMESTAMP
                    obj_modified
                    obj_commented
                                                    TIMESTAMP
                                                    TIMESTAMP
                                                                  }­ NOT NULL DEFAULT CURRENT_TIMESTAMP
                    obj_marks_count                 INT4
                    obj_marks_rating                FLOAT8         }­ rate everything!
                    obj_tsvector                    tsvector       — Almost all business objects need FTS




            user2obj                                group

     u2o_user_obj_id                         user                  comment
     u2o_obj_obj_id
     u2o_mark                                               comment_author_obj_id
     u2o_is_favorite                                        comment_text

Using PostgreSQL In Web 2.0 Applications
Rate And Comment Everything
   create table comment (
      obj_id INT8 not null default 
   (((nextval('comment_obj_id_seq'::regclass) * 223072849) % 
   (1000000000)::bigint) + 41000000000)
        constraint c_obj_comment_obj_id check 
           (obj_id between 41000000000 and 41999999999),
      comment_author_obj_id INT8,
      comment_body VARCHAR (2000) NOT NULL,
      constraint PK_MESSAGE primary key (obj_id)
   )
   inherits (obj);

   ­­ ID generation scheme:
   ­­ nextID = (N mod Y) * X + S, 
   ­­        where X & Y are co­primes, and S is an interval shift 

   ­­ Use separate sequence per each table!

   ­­ do not forget:
   SET constraint_exclusion ON;

Using PostgreSQL In Web 2.0 Applications
Build your Google Maps mashup:
                    with PostgreSQL it's easy
        Ways to store & index geo data in PostgreSQL:
              two integer columns and B­tree
              point column and R­tree                   MirTesen.ru
              PostGIS
              pgSphere                    GiST
              Q3C




Using PostgreSQL In Web 2.0 Applications
Conclusion

        PostgreSQL provides a great set of capabilities to 
         meet Web 2.0 developer needs
        PostgreSQL allows to develop quickly, w/o losing 
         quality




Using PostgreSQL In Web 2.0 Applications
Contacts
      ●   nikolay@samokhvalov.com
      ●   Blog: http://nikolay.samokhvalov.com
      ●   XMPP/GTalk: samokhvalov@gmail.com
      ●   Skype: samokhvalov OR postgresmen
      ●   +7 905 783 9804




Using PostgreSQL In Web 2.0 Applications

More Related Content

Viewers also liked

Viewers also liked (20)

20080214 Rupg Meeting1 Whatisnewpostgresql8.3
20080214 Rupg Meeting1 Whatisnewpostgresql8.320080214 Rupg Meeting1 Whatisnewpostgresql8.3
20080214 Rupg Meeting1 Whatisnewpostgresql8.3
 
20071002 Samag2007 Whats New In Postgresql8.3
20071002 Samag2007 Whats New In Postgresql8.320071002 Samag2007 Whats New In Postgresql8.3
20071002 Samag2007 Whats New In Postgresql8.3
 
20070925 Highload2007 Momjian Features
20070925 Highload2007 Momjian Features20070925 Highload2007 Momjian Features
20070925 Highload2007 Momjian Features
 
20071002 Samag2007 Whats New In Postgresql8.3
20071002 Samag2007 Whats New In Postgresql8.320071002 Samag2007 Whats New In Postgresql8.3
20071002 Samag2007 Whats New In Postgresql8.3
 
Natureza
NaturezaNatureza
Natureza
 
Uu 10 1998
Uu 10 1998Uu 10 1998
Uu 10 1998
 
Gosta
GostaGosta
Gosta
 
香港六合彩
香港六合彩香港六合彩
香港六合彩
 
Uu 15 1992
Uu 15 1992Uu 15 1992
Uu 15 1992
 
Uu 24 1992
Uu 24 1992Uu 24 1992
Uu 24 1992
 
Aoc Terra Peternella&Josevisser..Slangen
Aoc Terra Peternella&Josevisser..SlangenAoc Terra Peternella&Josevisser..Slangen
Aoc Terra Peternella&Josevisser..Slangen
 
world café
world caféworld café
world café
 
Uu 05 1994
Uu 05 1994Uu 05 1994
Uu 05 1994
 
Uu 08 1985
Uu 08 1985Uu 08 1985
Uu 08 1985
 
Uu 21 1999
Uu 21 1999Uu 21 1999
Uu 21 1999
 
Uu 03 1989
Uu 03 1989Uu 03 1989
Uu 03 1989
 
Uu 21 1999 Pjls
Uu 21 1999 PjlsUu 21 1999 Pjls
Uu 21 1999 Pjls
 
Hezurrak
HezurrakHezurrak
Hezurrak
 
Tecnologia
TecnologiaTecnologia
Tecnologia
 
Uu 07 1997
Uu 07 1997Uu 07 1997
Uu 07 1997
 

Similar to 20080330 Postgresqlconference2008 Pg In Web2.0 Samokhvalov

Template based framework for rapid fast development of enterprise applications
Template based framework for rapid fast development of enterprise applicationsTemplate based framework for rapid fast development of enterprise applications
Template based framework for rapid fast development of enterprise applicationseSAT Journals
 
Template based framework for rapid fast development
Template based framework for rapid fast developmentTemplate based framework for rapid fast development
Template based framework for rapid fast developmenteSAT Publishing House
 
So You Want to Write an Exporter
So You Want to Write an ExporterSo You Want to Write an Exporter
So You Want to Write an ExporterBrian Brazil
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2Long Nguyen
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2divzi1913
 
Struts 2 Overview
Struts 2 OverviewStruts 2 Overview
Struts 2 Overviewskill-guru
 
Salesforce integration questions
Salesforce integration questionsSalesforce integration questions
Salesforce integration questionsDebabrat Rout
 
Scalable AutoML for Time Series Forecasting using Ray
Scalable AutoML for Time Series Forecasting using RayScalable AutoML for Time Series Forecasting using Ray
Scalable AutoML for Time Series Forecasting using RayDatabricks
 
Multi-tenancy with Rails
Multi-tenancy with RailsMulti-tenancy with Rails
Multi-tenancy with RailsPaul Gallagher
 
Elasticsearch a real-time distributed search and analytics engine
Elasticsearch a real-time distributed search and analytics engineElasticsearch a real-time distributed search and analytics engine
Elasticsearch a real-time distributed search and analytics enginegautam kumar
 
Qtp interview questions
Qtp interview questionsQtp interview questions
Qtp interview questionsRamu Palanki
 
Qtp interview questions
Qtp interview questionsQtp interview questions
Qtp interview questionsRamu Palanki
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalystdwm042
 
Nhibernatethe Orm For Net Platform 1226744632929962 8
Nhibernatethe Orm For Net Platform 1226744632929962 8Nhibernatethe Orm For Net Platform 1226744632929962 8
Nhibernatethe Orm For Net Platform 1226744632929962 8Nicolas Thon
 
Nancy CLI. Automated Database Experiments
Nancy CLI. Automated Database ExperimentsNancy CLI. Automated Database Experiments
Nancy CLI. Automated Database ExperimentsNikolay Samokhvalov
 
Scalable And Incremental Data Profiling With Spark
Scalable And Incremental Data Profiling With SparkScalable And Incremental Data Profiling With Spark
Scalable And Incremental Data Profiling With SparkJen Aman
 
Java on Google App engine
Java on Google App engineJava on Google App engine
Java on Google App engineMichael Parker
 
Complex realtime event analytics using BigQuery @Crunch Warmup
Complex realtime event analytics using BigQuery @Crunch WarmupComplex realtime event analytics using BigQuery @Crunch Warmup
Complex realtime event analytics using BigQuery @Crunch WarmupMárton Kodok
 
Compass Framework
Compass FrameworkCompass Framework
Compass FrameworkLukas Vlcek
 

Similar to 20080330 Postgresqlconference2008 Pg In Web2.0 Samokhvalov (20)

Template based framework for rapid fast development of enterprise applications
Template based framework for rapid fast development of enterprise applicationsTemplate based framework for rapid fast development of enterprise applications
Template based framework for rapid fast development of enterprise applications
 
Template based framework for rapid fast development
Template based framework for rapid fast developmentTemplate based framework for rapid fast development
Template based framework for rapid fast development
 
So You Want to Write an Exporter
So You Want to Write an ExporterSo You Want to Write an Exporter
So You Want to Write an Exporter
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
 
Struts 2 Overview
Struts 2 OverviewStruts 2 Overview
Struts 2 Overview
 
Salesforce integration questions
Salesforce integration questionsSalesforce integration questions
Salesforce integration questions
 
Scalable AutoML for Time Series Forecasting using Ray
Scalable AutoML for Time Series Forecasting using RayScalable AutoML for Time Series Forecasting using Ray
Scalable AutoML for Time Series Forecasting using Ray
 
Multi-tenancy with Rails
Multi-tenancy with RailsMulti-tenancy with Rails
Multi-tenancy with Rails
 
Distributed Tracing
Distributed TracingDistributed Tracing
Distributed Tracing
 
Elasticsearch a real-time distributed search and analytics engine
Elasticsearch a real-time distributed search and analytics engineElasticsearch a real-time distributed search and analytics engine
Elasticsearch a real-time distributed search and analytics engine
 
Qtp interview questions
Qtp interview questionsQtp interview questions
Qtp interview questions
 
Qtp interview questions
Qtp interview questionsQtp interview questions
Qtp interview questions
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
Nhibernatethe Orm For Net Platform 1226744632929962 8
Nhibernatethe Orm For Net Platform 1226744632929962 8Nhibernatethe Orm For Net Platform 1226744632929962 8
Nhibernatethe Orm For Net Platform 1226744632929962 8
 
Nancy CLI. Automated Database Experiments
Nancy CLI. Automated Database ExperimentsNancy CLI. Automated Database Experiments
Nancy CLI. Automated Database Experiments
 
Scalable And Incremental Data Profiling With Spark
Scalable And Incremental Data Profiling With SparkScalable And Incremental Data Profiling With Spark
Scalable And Incremental Data Profiling With Spark
 
Java on Google App engine
Java on Google App engineJava on Google App engine
Java on Google App engine
 
Complex realtime event analytics using BigQuery @Crunch Warmup
Complex realtime event analytics using BigQuery @Crunch WarmupComplex realtime event analytics using BigQuery @Crunch Warmup
Complex realtime event analytics using BigQuery @Crunch Warmup
 
Compass Framework
Compass FrameworkCompass Framework
Compass Framework
 

More from Nikolay Samokhvalov

Эксперименты с Postgres в Docker и облаках — оптимизация настроек и схемы ва...
 Эксперименты с Postgres в Docker и облаках — оптимизация настроек и схемы ва... Эксперименты с Postgres в Docker и облаках — оптимизация настроек и схемы ва...
Эксперименты с Postgres в Docker и облаках — оптимизация настроек и схемы ва...Nikolay Samokhvalov
 
Промышленный подход к тюнингу PostgreSQL: эксперименты над базами данных
Промышленный подход к тюнингу PostgreSQL: эксперименты над базами данныхПромышленный подход к тюнингу PostgreSQL: эксперименты над базами данных
Промышленный подход к тюнингу PostgreSQL: эксперименты над базами данныхNikolay Samokhvalov
 
The Art of Database Experiments – PostgresConf Silicon Valley 2018 / San Jose
The Art of Database Experiments – PostgresConf Silicon Valley 2018 / San JoseThe Art of Database Experiments – PostgresConf Silicon Valley 2018 / San Jose
The Art of Database Experiments – PostgresConf Silicon Valley 2018 / San JoseNikolay Samokhvalov
 
#RuPostgresLive 4: как писать и читать сложные SQL-запросы
#RuPostgresLive 4: как писать и читать сложные SQL-запросы#RuPostgresLive 4: как писать и читать сложные SQL-запросы
#RuPostgresLive 4: как писать и читать сложные SQL-запросыNikolay Samokhvalov
 
#RuPostgresLive 4: как писать и читать сложные SQL-запросы
#RuPostgresLive 4: как писать и читать сложные SQL-запросы#RuPostgresLive 4: как писать и читать сложные SQL-запросы
#RuPostgresLive 4: как писать и читать сложные SQL-запросыNikolay Samokhvalov
 
Database First! О распространённых ошибках использования РСУБД
Database First! О распространённых ошибках использования РСУБДDatabase First! О распространённых ошибках использования РСУБД
Database First! О распространённых ошибках использования РСУБДNikolay Samokhvalov
 
#RuPostges в Yandex, эпизод 3. Что же нового в PostgreSQL 9.6
#RuPostges в Yandex, эпизод 3. Что же нового в PostgreSQL 9.6#RuPostges в Yandex, эпизод 3. Что же нового в PostgreSQL 9.6
#RuPostges в Yandex, эпизод 3. Что же нового в PostgreSQL 9.6Nikolay Samokhvalov
 
#noBackend, или Как выжить в эпоху толстеющих клиентов
#noBackend, или Как выжить в эпоху толстеющих клиентов#noBackend, или Как выжить в эпоху толстеющих клиентов
#noBackend, или Как выжить в эпоху толстеющих клиентовNikolay Samokhvalov
 
#PostgreSQLRussia в банке Тинькофф, доклад №1
#PostgreSQLRussia в банке Тинькофф, доклад №1#PostgreSQLRussia в банке Тинькофф, доклад №1
#PostgreSQLRussia в банке Тинькофф, доклад №1Nikolay Samokhvalov
 
SFPUG 2015.11.20 lightning talk "PostgreSQL in Russia"
SFPUG 2015.11.20 lightning talk "PostgreSQL in Russia"SFPUG 2015.11.20 lightning talk "PostgreSQL in Russia"
SFPUG 2015.11.20 lightning talk "PostgreSQL in Russia"Nikolay Samokhvalov
 
Владимир Бородин: Как спать спокойно - 2015.10.14 PostgreSQLRussia.org meetu...
Владимир Бородин: Как спать спокойно - 2015.10.14 PostgreSQLRussia.org meetu...Владимир Бородин: Как спать спокойно - 2015.10.14 PostgreSQLRussia.org meetu...
Владимир Бородин: Как спать спокойно - 2015.10.14 PostgreSQLRussia.org meetu...Nikolay Samokhvalov
 
#PostgreSQLRussia 2015.09.15 - Николай Самохвалов - 5 главных особенностей Po...
#PostgreSQLRussia 2015.09.15 - Николай Самохвалов - 5 главных особенностей Po...#PostgreSQLRussia 2015.09.15 - Николай Самохвалов - 5 главных особенностей Po...
#PostgreSQLRussia 2015.09.15 - Николай Самохвалов - 5 главных особенностей Po...Nikolay Samokhvalov
 
#PostgreSQLRussia 2015.09.15 - Максим Трегубов, CUSTIS - Миграция из Oracle в...
#PostgreSQLRussia 2015.09.15 - Максим Трегубов, CUSTIS - Миграция из Oracle в...#PostgreSQLRussia 2015.09.15 - Максим Трегубов, CUSTIS - Миграция из Oracle в...
#PostgreSQLRussia 2015.09.15 - Максим Трегубов, CUSTIS - Миграция из Oracle в...Nikolay Samokhvalov
 
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...Nikolay Samokhvalov
 
2014.12.23 Николай Самохвалов, Ещё раз о JSON(b) в PostgreSQL 9.4
2014.12.23 Николай Самохвалов, Ещё раз о JSON(b) в PostgreSQL 9.42014.12.23 Николай Самохвалов, Ещё раз о JSON(b) в PostgreSQL 9.4
2014.12.23 Николай Самохвалов, Ещё раз о JSON(b) в PostgreSQL 9.4Nikolay Samokhvalov
 
2014.12.23 Александр Андреев, Parallels
2014.12.23 Александр Андреев, Parallels2014.12.23 Александр Андреев, Parallels
2014.12.23 Александр Андреев, ParallelsNikolay Samokhvalov
 
2014.10.15 Сергей Бурладян, Avito.ru
2014.10.15 Сергей Бурладян, Avito.ru2014.10.15 Сергей Бурладян, Avito.ru
2014.10.15 Сергей Бурладян, Avito.ruNikolay Samokhvalov
 
2014.10.15 Мурат Кабилов, Avito.ru #PostgreSQLRussia
2014.10.15 Мурат Кабилов, Avito.ru #PostgreSQLRussia2014.10.15 Мурат Кабилов, Avito.ru #PostgreSQLRussia
2014.10.15 Мурат Кабилов, Avito.ru #PostgreSQLRussiaNikolay Samokhvalov
 
2014.10.15 блиц-доклад PostgreSQL kNN search
2014.10.15 блиц-доклад PostgreSQL kNN search2014.10.15 блиц-доклад PostgreSQL kNN search
2014.10.15 блиц-доклад PostgreSQL kNN searchNikolay Samokhvalov
 

More from Nikolay Samokhvalov (20)

Эксперименты с Postgres в Docker и облаках — оптимизация настроек и схемы ва...
 Эксперименты с Postgres в Docker и облаках — оптимизация настроек и схемы ва... Эксперименты с Postgres в Docker и облаках — оптимизация настроек и схемы ва...
Эксперименты с Postgres в Docker и облаках — оптимизация настроек и схемы ва...
 
Промышленный подход к тюнингу PostgreSQL: эксперименты над базами данных
Промышленный подход к тюнингу PostgreSQL: эксперименты над базами данныхПромышленный подход к тюнингу PostgreSQL: эксперименты над базами данных
Промышленный подход к тюнингу PostgreSQL: эксперименты над базами данных
 
The Art of Database Experiments – PostgresConf Silicon Valley 2018 / San Jose
The Art of Database Experiments – PostgresConf Silicon Valley 2018 / San JoseThe Art of Database Experiments – PostgresConf Silicon Valley 2018 / San Jose
The Art of Database Experiments – PostgresConf Silicon Valley 2018 / San Jose
 
#RuPostgresLive 4: как писать и читать сложные SQL-запросы
#RuPostgresLive 4: как писать и читать сложные SQL-запросы#RuPostgresLive 4: как писать и читать сложные SQL-запросы
#RuPostgresLive 4: как писать и читать сложные SQL-запросы
 
#RuPostgresLive 4: как писать и читать сложные SQL-запросы
#RuPostgresLive 4: как писать и читать сложные SQL-запросы#RuPostgresLive 4: как писать и читать сложные SQL-запросы
#RuPostgresLive 4: как писать и читать сложные SQL-запросы
 
Database First! О распространённых ошибках использования РСУБД
Database First! О распространённых ошибках использования РСУБДDatabase First! О распространённых ошибках использования РСУБД
Database First! О распространённых ошибках использования РСУБД
 
2016.10.13 PostgreSQL in Russia
2016.10.13 PostgreSQL in Russia2016.10.13 PostgreSQL in Russia
2016.10.13 PostgreSQL in Russia
 
#RuPostges в Yandex, эпизод 3. Что же нового в PostgreSQL 9.6
#RuPostges в Yandex, эпизод 3. Что же нового в PostgreSQL 9.6#RuPostges в Yandex, эпизод 3. Что же нового в PostgreSQL 9.6
#RuPostges в Yandex, эпизод 3. Что же нового в PostgreSQL 9.6
 
#noBackend, или Как выжить в эпоху толстеющих клиентов
#noBackend, или Как выжить в эпоху толстеющих клиентов#noBackend, или Как выжить в эпоху толстеющих клиентов
#noBackend, или Как выжить в эпоху толстеющих клиентов
 
#PostgreSQLRussia в банке Тинькофф, доклад №1
#PostgreSQLRussia в банке Тинькофф, доклад №1#PostgreSQLRussia в банке Тинькофф, доклад №1
#PostgreSQLRussia в банке Тинькофф, доклад №1
 
SFPUG 2015.11.20 lightning talk "PostgreSQL in Russia"
SFPUG 2015.11.20 lightning talk "PostgreSQL in Russia"SFPUG 2015.11.20 lightning talk "PostgreSQL in Russia"
SFPUG 2015.11.20 lightning talk "PostgreSQL in Russia"
 
Владимир Бородин: Как спать спокойно - 2015.10.14 PostgreSQLRussia.org meetu...
Владимир Бородин: Как спать спокойно - 2015.10.14 PostgreSQLRussia.org meetu...Владимир Бородин: Как спать спокойно - 2015.10.14 PostgreSQLRussia.org meetu...
Владимир Бородин: Как спать спокойно - 2015.10.14 PostgreSQLRussia.org meetu...
 
#PostgreSQLRussia 2015.09.15 - Николай Самохвалов - 5 главных особенностей Po...
#PostgreSQLRussia 2015.09.15 - Николай Самохвалов - 5 главных особенностей Po...#PostgreSQLRussia 2015.09.15 - Николай Самохвалов - 5 главных особенностей Po...
#PostgreSQLRussia 2015.09.15 - Николай Самохвалов - 5 главных особенностей Po...
 
#PostgreSQLRussia 2015.09.15 - Максим Трегубов, CUSTIS - Миграция из Oracle в...
#PostgreSQLRussia 2015.09.15 - Максим Трегубов, CUSTIS - Миграция из Oracle в...#PostgreSQLRussia 2015.09.15 - Максим Трегубов, CUSTIS - Миграция из Oracle в...
#PostgreSQLRussia 2015.09.15 - Максим Трегубов, CUSTIS - Миграция из Oracle в...
 
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
Три вызова реляционным СУБД и новый PostgreSQL - #PostgreSQLRussia семинар по...
 
2014.12.23 Николай Самохвалов, Ещё раз о JSON(b) в PostgreSQL 9.4
2014.12.23 Николай Самохвалов, Ещё раз о JSON(b) в PostgreSQL 9.42014.12.23 Николай Самохвалов, Ещё раз о JSON(b) в PostgreSQL 9.4
2014.12.23 Николай Самохвалов, Ещё раз о JSON(b) в PostgreSQL 9.4
 
2014.12.23 Александр Андреев, Parallels
2014.12.23 Александр Андреев, Parallels2014.12.23 Александр Андреев, Parallels
2014.12.23 Александр Андреев, Parallels
 
2014.10.15 Сергей Бурладян, Avito.ru
2014.10.15 Сергей Бурладян, Avito.ru2014.10.15 Сергей Бурладян, Avito.ru
2014.10.15 Сергей Бурладян, Avito.ru
 
2014.10.15 Мурат Кабилов, Avito.ru #PostgreSQLRussia
2014.10.15 Мурат Кабилов, Avito.ru #PostgreSQLRussia2014.10.15 Мурат Кабилов, Avito.ru #PostgreSQLRussia
2014.10.15 Мурат Кабилов, Avito.ru #PostgreSQLRussia
 
2014.10.15 блиц-доклад PostgreSQL kNN search
2014.10.15 блиц-доклад PostgreSQL kNN search2014.10.15 блиц-доклад PostgreSQL kNN search
2014.10.15 блиц-доклад PostgreSQL kNN search
 

Recently uploaded

The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...Aggregage
 
Cracking the Cultural Competence Code.pptx
Cracking the Cultural Competence Code.pptxCracking the Cultural Competence Code.pptx
Cracking the Cultural Competence Code.pptxWorkforce Group
 
John Halpern sued for sexual assault.pdf
John Halpern sued for sexual assault.pdfJohn Halpern sued for sexual assault.pdf
John Halpern sued for sexual assault.pdfAmzadHosen3
 
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service AvailableCall Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service AvailableDipal Arora
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesDipal Arora
 
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...Lviv Startup Club
 
Organizational Transformation Lead with Culture
Organizational Transformation Lead with CultureOrganizational Transformation Lead with Culture
Organizational Transformation Lead with CultureSeta Wicaksana
 
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...anilsa9823
 
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...Any kyc Account
 
Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Neil Kimberley
 
Call Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine ServiceCall Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine Serviceritikaroy0888
 
A DAY IN THE LIFE OF A SALESMAN / WOMAN
A DAY IN THE LIFE OF A  SALESMAN / WOMANA DAY IN THE LIFE OF A  SALESMAN / WOMAN
A DAY IN THE LIFE OF A SALESMAN / WOMANIlamathiKannappan
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Servicediscovermytutordmt
 
HONOR Veterans Event Keynote by Michael Hawkins
HONOR Veterans Event Keynote by Michael HawkinsHONOR Veterans Event Keynote by Michael Hawkins
HONOR Veterans Event Keynote by Michael HawkinsMichael W. Hawkins
 
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...rajveerescorts2022
 
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLMONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLSeo
 
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxB.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxpriyanshujha201
 
Pharma Works Profile of Karan Communications
Pharma Works Profile of Karan CommunicationsPharma Works Profile of Karan Communications
Pharma Works Profile of Karan Communicationskarancommunications
 

Recently uploaded (20)

The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
 
Cracking the Cultural Competence Code.pptx
Cracking the Cultural Competence Code.pptxCracking the Cultural Competence Code.pptx
Cracking the Cultural Competence Code.pptx
 
John Halpern sued for sexual assault.pdf
John Halpern sued for sexual assault.pdfJohn Halpern sued for sexual assault.pdf
John Halpern sued for sexual assault.pdf
 
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service AvailableCall Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
 
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
 
Organizational Transformation Lead with Culture
Organizational Transformation Lead with CultureOrganizational Transformation Lead with Culture
Organizational Transformation Lead with Culture
 
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
 
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
 
Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023
 
Call Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine ServiceCall Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine Service
 
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pillsMifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
 
A DAY IN THE LIFE OF A SALESMAN / WOMAN
A DAY IN THE LIFE OF A  SALESMAN / WOMANA DAY IN THE LIFE OF A  SALESMAN / WOMAN
A DAY IN THE LIFE OF A SALESMAN / WOMAN
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Service
 
HONOR Veterans Event Keynote by Michael Hawkins
HONOR Veterans Event Keynote by Michael HawkinsHONOR Veterans Event Keynote by Michael Hawkins
HONOR Veterans Event Keynote by Michael Hawkins
 
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
 
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLMONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
 
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxB.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
 
Pharma Works Profile of Karan Communications
Pharma Works Profile of Karan CommunicationsPharma Works Profile of Karan Communications
Pharma Works Profile of Karan Communications
 
Forklift Operations: Safety through Cartoons
Forklift Operations: Safety through CartoonsForklift Operations: Safety through Cartoons
Forklift Operations: Safety through Cartoons
 

20080330 Postgresqlconference2008 Pg In Web2.0 Samokhvalov

  • 1. Using PostgreSQL In Web 2.0 Applications How PostgreSQL helps to build Web 2.0 Apps Nikolay Samokhvalov Postgresmen, LLC (Moscow, Russia) PostgreSQL Conference East 2008
  • 3. What Is Web 2.0? For users:  Collaborative web (UGC*, comments, rating system, etc)  Web applications, not web sites (AJAX, more interaction)  Web as a platform (interoperability, RSS, microformats, etc)  Rounded corners, mirrored logos etc :­) *)  UGC — user­generated content Using PostgreSQL In Web 2.0 Applications
  • 4. What Is Web 2.0? For software developers it means: more users more developers more brands more competitors on the market higher rapidly number of users, larger pageviews, TPS, rates of changing development, data etc: business volumes shorter iterations requirements N = et Better technologies help to win! Using PostgreSQL In Web 2.0 Applications
  • 5. Why PostgreSQL? 1. Performance, scalability 2. Reliability 3. Powerful capabilities 4. Standards compliance, proper approaches 5. Freedom Using PostgreSQL In Web 2.0 Applications
  • 6. Why PostgreSQL? 1. Performance, scalability 2. Reliability } Quality 3. Powerful capabilities } Development efficiency 4. Standards compliance, proper approaches 5. Freedom } HR Using PostgreSQL In Web 2.0 Applications
  • 7. How to Deal With UGC? 1. Taxonomy ● Catalogs 2. Folksonomy ● Tags 3. Hybrid, two ways: ● Tags + Catalogs ● Both users and editors control Catalogs Using PostgreSQL In Web 2.0 Applications
  • 8. UGC: Taxonomy 1. Taxonomy (Catalogs) ● EAV, where ATTRIBUTE table is [almost] constant ● intarray / hstore Using PostgreSQL In Web 2.0 Applications
  • 9. EAV: Entity­Attibute­Value Entity Value Attribute Using PostgreSQL In Web 2.0 Applications
  • 10. intarray / hstore item obj_id INT8 item_section_id INT8 item_vendor_id INT8 item_model_id INT8 item_year INT2 item_price NUMERIC(30,6) item_props intarray What about performance? ● This approach allows to save much space ● Performance is good if you mix GiST/GIN search with FTS search ● Better to cache tag values in external cache (e.g. Memcache) if you use  intarray, but in this case using FTS is a bit harder Using PostgreSQL In Web 2.0 Applications
  • 11. UGC: Folksonomy 1. Folksonomy (Tags) 1. EAV (again), user­controlled ATTRIBUTE table 2. intarray / hstore (again)     — it's just almost the same, you just give control to your users Tags: Using PostgreSQL In Web 2.0 Applications
  • 12. UGC: Hybrid 1. Hybrid, two ways: 1. Tags + Catalogs —  common practice 2. Both users and editors control Catalogs —  is the most interesting, but is the most difficult to implement and  maintain  ● UGC­only catalog entries are not shown in common <SELECT>  lists, they are waiting for editors approval. ● 'Merge' procedure is really complicated (merge UGC with editors'  data; merge duplicates, synonyms, etc). ● FTS (stemming, morphology, thesaurus), pg_trgm, metaphone,  soundex, etc may help. BUT: human work is still needed. Using PostgreSQL In Web 2.0 Applications
  • 13. UGC: More About Tags 1. Use FTS (tsearch2) to integrate tag searching in your search subsystem: ● use FTS categories to differ tag words from mere words when needed; ● to process tags, use separate FTS configuration, if needed. 2. Use quot;prefix searchquot; for tag searching, but it's not straightforward (wait for  the next slides ;­) ) Using PostgreSQL In Web 2.0 Applications
  • 14. UGC: Tags And Prefix Search quot;Prefix searchquot; helps to build smth like this: If you use simple LIKE 'bla%' the result will be somewhat dissapointing: test=# EXPLAIN ANALYZE SELECT * FROM tag WHERE tag_name LIKE 'bla%';                               QUERY PLAN ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­  Seq Scan on tag  (cost=0.00..6182.75 rows=1 width=105) (actual time=0.951..102.779 rows=162 loops=1)    Filter: ((tag_name)::text ~~ 'bla%'::text)  Total runtime: 102.871 ms (3 rows) Notice: ~300k unique tags in the table Using PostgreSQL In Web 2.0 Applications
  • 15. Tags And Prefix Search: The Proper Solution 1. Use text_pattern_ops to speed up LIKE 'bla%' queries: test=# CREATE INDEX i_tag_prefix ON tag              USING btree(lower(tag_name) text_pattern_ops); CREATE INDEX test=# EXPLAIN ANALYZE SELECT * FROM tag              WHERE lower(tag_name) LIKE lower('bla%');                              QUERY PLAN ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­  Bitmap Heap Scan on tag  (cost=43.55..2356.16 rows=1096 width=105) (actual time=0.164..0.791 rows=235 loops=1)    Filter: (lower((tag_name)::text) ~~ 'bla%'::text)    ­>  Bitmap Index Scan on i_tag_prefix  (cost=0.00..43.28 rows=1096 width=0) (actual time=0.116..0.116 rows=235 loops=1)          Index Cond: ((lower((tag_name)::text) ~>=~ 'bla'::text) AND (lower((tag_name)::text) ~<~ 'мис'::text))  Total runtime: 0.885 ms (5 rows) Notices: (1) ILIKE is not acceptable, so use lower(); (2) be careful using non­ASCII charactes  (i.e. it's OK for Russian UTF­8 except minor 'ё' & 'Ё' chars) Using PostgreSQL In Web 2.0 Applications
  • 16. Tags And Prefix Search: The Proper Solution 2. Create tag_words (unique tag words) table to work with words, not with phrases: CREATE TABLE tag_words AS      SELECT DISTINCT word      FROM ts_stat('SELECT to_tsvector(tag_name) FROM tag'); ­­ heavy DROP INDEX i_tag_prefix; CREATE INDEX i_tag_fts ON tag USING gin(to_tsvector(tag_name)); CREATE INDEX i_tag_words_prefix ON tag_words      USING btree(lower(word) text_pattern_ops); test=# EXPLAIN ANALYZE    SELECT * FROM tag    WHERE to_tsvector('utf8_russian'::regconfig, tag_name::text)          @@ to_tsquery('utf8_russian', '(' || (           SELECT array_to_string(array_accum(lower(word)), '|')           FROM tag_words           WHERE lower(word) LIKE 'bla%') || ')'); ­­ add '...&word1&word2' if needed /* plan is omitted */  Total runtime: 13.243 ms (11 rows) Notices: (1) better to limit number of tag words found by the inner query (e.g. ordering by word  age — dirty but it works); (2) word order in original query is lost, unfortunately; (3) GIN indexes  are better than GiST here Using PostgreSQL In Web 2.0 Applications
  • 17. Rate And Comment Everything    PostgreSQL Inheritance helps to achieve development efficiency obj obj_id      INT8 — Not SERIAL, wait for the next slide to see details obj_status_did INT8 — Dictionary value obj_creator_obj_id INT8 — ID of user who created the record (if applicable) obj_created TIMESTAMP obj_modified obj_commented TIMESTAMP TIMESTAMP }­ NOT NULL DEFAULT CURRENT_TIMESTAMP obj_marks_count INT4 obj_marks_rating FLOAT8 }­ rate everything! obj_tsvector tsvector — Almost all business objects need FTS user2obj group u2o_user_obj_id user comment u2o_obj_obj_id u2o_mark comment_author_obj_id u2o_is_favorite comment_text Using PostgreSQL In Web 2.0 Applications
  • 18. Rate And Comment Everything create table comment (    obj_id INT8 not null default  (((nextval('comment_obj_id_seq'::regclass) * 223072849) %  (1000000000)::bigint) + 41000000000)      constraint c_obj_comment_obj_id check          (obj_id between 41000000000 and 41999999999),    comment_author_obj_id INT8,    comment_body VARCHAR (2000) NOT NULL,    constraint PK_MESSAGE primary key (obj_id) ) inherits (obj); ­­ ID generation scheme: ­­ nextID = (N mod Y) * X + S,  ­­        where X & Y are co­primes, and S is an interval shift  ­­ Use separate sequence per each table! ­­ do not forget: SET constraint_exclusion ON; Using PostgreSQL In Web 2.0 Applications
  • 19. Build your Google Maps mashup: with PostgreSQL it's easy  Ways to store & index geo data in PostgreSQL:  two integer columns and B­tree  point column and R­tree MirTesen.ru  PostGIS  pgSphere GiST  Q3C Using PostgreSQL In Web 2.0 Applications
  • 20. Conclusion  PostgreSQL provides a great set of capabilities to  meet Web 2.0 developer needs  PostgreSQL allows to develop quickly, w/o losing  quality Using PostgreSQL In Web 2.0 Applications
  • 21. Contacts ● nikolay@samokhvalov.com ● Blog: http://nikolay.samokhvalov.com ● XMPP/GTalk: samokhvalov@gmail.com ● Skype: samokhvalov OR postgresmen ● +7 905 783 9804 Using PostgreSQL In Web 2.0 Applications