SlideShare a Scribd company logo
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

20080214 Rupg Meeting1 Whatisnewpostgresql8.3
20080214 Rupg Meeting1 Whatisnewpostgresql8.320080214 Rupg Meeting1 Whatisnewpostgresql8.3
20080214 Rupg Meeting1 Whatisnewpostgresql8.3Nikolay Samokhvalov
 
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.3Nikolay Samokhvalov
 
20070925 Highload2007 Momjian Features
20070925 Highload2007 Momjian Features20070925 Highload2007 Momjian Features
20070925 Highload2007 Momjian FeaturesNikolay Samokhvalov
 
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.3Nikolay Samokhvalov
 
香港六合彩
香港六合彩香港六合彩
香港六合彩
zazhong
 
Aoc Terra Peternella&Josevisser..Slangen
Aoc Terra Peternella&Josevisser..SlangenAoc Terra Peternella&Josevisser..Slangen
Aoc Terra Peternella&Josevisser..Slangennicowb
 
world café
world caféworld café
world café
ppalacios
 
Hezurrak
HezurrakHezurrak
Hezurraknahia
 

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 applications
eSAT 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 development
eSAT 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 Exporter
Brian 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 Overview
skill-guru
 
Salesforce integration questions
Salesforce integration questionsSalesforce integration questions
Salesforce integration questions
Debabrat 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 Ray
Databricks
 
Multi-tenancy with Rails
Multi-tenancy with RailsMulti-tenancy with Rails
Multi-tenancy with Rails
Paul Gallagher
 
Distributed Tracing
Distributed TracingDistributed Tracing
Distributed Tracing
distributedtracing
 
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
gautam 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 catalyst
dwm042
 
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 Experiments
Nikolay 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 Spark
Jen Aman
 
Java on Google App engine
Java on Google App engineJava on Google App engine
Java on Google App engine
Michael 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 Warmup
Márton Kodok
 
Compass Framework
Compass FrameworkCompass Framework
Compass Framework
Lukas 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 Jose
Nikolay 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
 
2016.10.13 PostgreSQL in Russia
2016.10.13 PostgreSQL in Russia2016.10.13 PostgreSQL in Russia
2016.10.13 PostgreSQL in Russia
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.6
Nikolay Samokhvalov
 
#noBackend, или Как выжить в эпоху толстеющих клиентов
#noBackend, или Как выжить в эпоху толстеющих клиентов#noBackend, или Как выжить в эпоху толстеющих клиентов
#noBackend, или Как выжить в эпоху толстеющих клиентов
Nikolay Samokhvalov
 
#PostgreSQLRussia в банке Тинькофф, доклад №1
#PostgreSQLRussia в банке Тинькофф, доклад №1#PostgreSQLRussia в банке Тинькофф, доклад №1
#PostgreSQLRussia в банке Тинькофф, доклад №1
Nikolay 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.4
Nikolay Samokhvalov
 
2014.12.23 Александр Андреев, Parallels
2014.12.23 Александр Андреев, Parallels2014.12.23 Александр Андреев, Parallels
2014.12.23 Александр Андреев, Parallels
Nikolay Samokhvalov
 
2014.10.15 Сергей Бурладян, Avito.ru
2014.10.15 Сергей Бурладян, Avito.ru2014.10.15 Сергей Бурладян, Avito.ru
2014.10.15 Сергей Бурладян, Avito.ru
Nikolay Samokhvalov
 
2014.10.15 Мурат Кабилов, Avito.ru #PostgreSQLRussia
2014.10.15 Мурат Кабилов, Avito.ru #PostgreSQLRussia2014.10.15 Мурат Кабилов, Avito.ru #PostgreSQLRussia
2014.10.15 Мурат Кабилов, Avito.ru #PostgreSQLRussia
Nikolay Samokhvalov
 
2014.10.15 блиц-доклад PostgreSQL kNN search
2014.10.15 блиц-доклад PostgreSQL kNN search2014.10.15 блиц-доклад PostgreSQL kNN search
2014.10.15 блиц-доклад PostgreSQL kNN search
Nikolay 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

Enterprise Excellence is Inclusive Excellence.pdf
Enterprise Excellence is Inclusive Excellence.pdfEnterprise Excellence is Inclusive Excellence.pdf
Enterprise Excellence is Inclusive Excellence.pdf
KaiNexus
 
Maksym Vyshnivetskyi: PMO Quality Management (UA)
Maksym Vyshnivetskyi: PMO Quality Management (UA)Maksym Vyshnivetskyi: PMO Quality Management (UA)
Maksym Vyshnivetskyi: PMO Quality Management (UA)
Lviv Startup Club
 
Cree_Rey_BrandIdentityKit.PDF_PersonalBd
Cree_Rey_BrandIdentityKit.PDF_PersonalBdCree_Rey_BrandIdentityKit.PDF_PersonalBd
Cree_Rey_BrandIdentityKit.PDF_PersonalBd
creerey
 
Company Valuation webinar series - Tuesday, 4 June 2024
Company Valuation webinar series - Tuesday, 4 June 2024Company Valuation webinar series - Tuesday, 4 June 2024
Company Valuation webinar series - Tuesday, 4 June 2024
FelixPerez547899
 
Putting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptxPutting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptx
Cynthia Clay
 
Authentically Social by Corey Perlman - EO Puerto Rico
Authentically Social by Corey Perlman - EO Puerto RicoAuthentically Social by Corey Perlman - EO Puerto Rico
Authentically Social by Corey Perlman - EO Puerto Rico
Corey Perlman, Social Media Speaker and Consultant
 
The Influence of Marketing Strategy and Market Competition on Business Perfor...
The Influence of Marketing Strategy and Market Competition on Business Perfor...The Influence of Marketing Strategy and Market Competition on Business Perfor...
The Influence of Marketing Strategy and Market Competition on Business Perfor...
Adam Smith
 
Organizational Change Leadership Agile Tour Geneve 2024
Organizational Change Leadership Agile Tour Geneve 2024Organizational Change Leadership Agile Tour Geneve 2024
Organizational Change Leadership Agile Tour Geneve 2024
Kirill Klimov
 
In the Adani-Hindenburg case, what is SEBI investigating.pptx
In the Adani-Hindenburg case, what is SEBI investigating.pptxIn the Adani-Hindenburg case, what is SEBI investigating.pptx
In the Adani-Hindenburg case, what is SEBI investigating.pptx
Adani case
 
Event Report - SAP Sapphire 2024 Orlando - lots of innovation and old challenges
Event Report - SAP Sapphire 2024 Orlando - lots of innovation and old challengesEvent Report - SAP Sapphire 2024 Orlando - lots of innovation and old challenges
Event Report - SAP Sapphire 2024 Orlando - lots of innovation and old challenges
Holger Mueller
 
Business Valuation Principles for Entrepreneurs
Business Valuation Principles for EntrepreneursBusiness Valuation Principles for Entrepreneurs
Business Valuation Principles for Entrepreneurs
Ben Wann
 
3.0 Project 2_ Developing My Brand Identity Kit.pptx
3.0 Project 2_ Developing My Brand Identity Kit.pptx3.0 Project 2_ Developing My Brand Identity Kit.pptx
3.0 Project 2_ Developing My Brand Identity Kit.pptx
tanyjahb
 
VAT Registration Outlined In UAE: Benefits and Requirements
VAT Registration Outlined In UAE: Benefits and RequirementsVAT Registration Outlined In UAE: Benefits and Requirements
VAT Registration Outlined In UAE: Benefits and Requirements
uae taxgpt
 
ModelingMarketingStrategiesMKS.CollumbiaUniversitypdf
ModelingMarketingStrategiesMKS.CollumbiaUniversitypdfModelingMarketingStrategiesMKS.CollumbiaUniversitypdf
ModelingMarketingStrategiesMKS.CollumbiaUniversitypdf
fisherameliaisabella
 
BeMetals Investor Presentation_June 1, 2024.pdf
BeMetals Investor Presentation_June 1, 2024.pdfBeMetals Investor Presentation_June 1, 2024.pdf
BeMetals Investor Presentation_June 1, 2024.pdf
DerekIwanaka1
 
Bài tập - Tiếng anh 11 Global Success UNIT 1 - Bản HS.doc.pdf
Bài tập - Tiếng anh 11 Global Success UNIT 1 - Bản HS.doc.pdfBài tập - Tiếng anh 11 Global Success UNIT 1 - Bản HS.doc.pdf
Bài tập - Tiếng anh 11 Global Success UNIT 1 - Bản HS.doc.pdf
daothibichhang1
 
Set off and carry forward of losses and assessment of individuals.pptx
Set off and carry forward of losses and assessment of individuals.pptxSet off and carry forward of losses and assessment of individuals.pptx
Set off and carry forward of losses and assessment of individuals.pptx
HARSHITHV26
 
Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...
Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...
Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...
bosssp10
 
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdfSearch Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Arihant Webtech Pvt. Ltd
 
Evgen Osmak: Methods of key project parameters estimation: from the shaman-in...
Evgen Osmak: Methods of key project parameters estimation: from the shaman-in...Evgen Osmak: Methods of key project parameters estimation: from the shaman-in...
Evgen Osmak: Methods of key project parameters estimation: from the shaman-in...
Lviv Startup Club
 

Recently uploaded (20)

Enterprise Excellence is Inclusive Excellence.pdf
Enterprise Excellence is Inclusive Excellence.pdfEnterprise Excellence is Inclusive Excellence.pdf
Enterprise Excellence is Inclusive Excellence.pdf
 
Maksym Vyshnivetskyi: PMO Quality Management (UA)
Maksym Vyshnivetskyi: PMO Quality Management (UA)Maksym Vyshnivetskyi: PMO Quality Management (UA)
Maksym Vyshnivetskyi: PMO Quality Management (UA)
 
Cree_Rey_BrandIdentityKit.PDF_PersonalBd
Cree_Rey_BrandIdentityKit.PDF_PersonalBdCree_Rey_BrandIdentityKit.PDF_PersonalBd
Cree_Rey_BrandIdentityKit.PDF_PersonalBd
 
Company Valuation webinar series - Tuesday, 4 June 2024
Company Valuation webinar series - Tuesday, 4 June 2024Company Valuation webinar series - Tuesday, 4 June 2024
Company Valuation webinar series - Tuesday, 4 June 2024
 
Putting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptxPutting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptx
 
Authentically Social by Corey Perlman - EO Puerto Rico
Authentically Social by Corey Perlman - EO Puerto RicoAuthentically Social by Corey Perlman - EO Puerto Rico
Authentically Social by Corey Perlman - EO Puerto Rico
 
The Influence of Marketing Strategy and Market Competition on Business Perfor...
The Influence of Marketing Strategy and Market Competition on Business Perfor...The Influence of Marketing Strategy and Market Competition on Business Perfor...
The Influence of Marketing Strategy and Market Competition on Business Perfor...
 
Organizational Change Leadership Agile Tour Geneve 2024
Organizational Change Leadership Agile Tour Geneve 2024Organizational Change Leadership Agile Tour Geneve 2024
Organizational Change Leadership Agile Tour Geneve 2024
 
In the Adani-Hindenburg case, what is SEBI investigating.pptx
In the Adani-Hindenburg case, what is SEBI investigating.pptxIn the Adani-Hindenburg case, what is SEBI investigating.pptx
In the Adani-Hindenburg case, what is SEBI investigating.pptx
 
Event Report - SAP Sapphire 2024 Orlando - lots of innovation and old challenges
Event Report - SAP Sapphire 2024 Orlando - lots of innovation and old challengesEvent Report - SAP Sapphire 2024 Orlando - lots of innovation and old challenges
Event Report - SAP Sapphire 2024 Orlando - lots of innovation and old challenges
 
Business Valuation Principles for Entrepreneurs
Business Valuation Principles for EntrepreneursBusiness Valuation Principles for Entrepreneurs
Business Valuation Principles for Entrepreneurs
 
3.0 Project 2_ Developing My Brand Identity Kit.pptx
3.0 Project 2_ Developing My Brand Identity Kit.pptx3.0 Project 2_ Developing My Brand Identity Kit.pptx
3.0 Project 2_ Developing My Brand Identity Kit.pptx
 
VAT Registration Outlined In UAE: Benefits and Requirements
VAT Registration Outlined In UAE: Benefits and RequirementsVAT Registration Outlined In UAE: Benefits and Requirements
VAT Registration Outlined In UAE: Benefits and Requirements
 
ModelingMarketingStrategiesMKS.CollumbiaUniversitypdf
ModelingMarketingStrategiesMKS.CollumbiaUniversitypdfModelingMarketingStrategiesMKS.CollumbiaUniversitypdf
ModelingMarketingStrategiesMKS.CollumbiaUniversitypdf
 
BeMetals Investor Presentation_June 1, 2024.pdf
BeMetals Investor Presentation_June 1, 2024.pdfBeMetals Investor Presentation_June 1, 2024.pdf
BeMetals Investor Presentation_June 1, 2024.pdf
 
Bài tập - Tiếng anh 11 Global Success UNIT 1 - Bản HS.doc.pdf
Bài tập - Tiếng anh 11 Global Success UNIT 1 - Bản HS.doc.pdfBài tập - Tiếng anh 11 Global Success UNIT 1 - Bản HS.doc.pdf
Bài tập - Tiếng anh 11 Global Success UNIT 1 - Bản HS.doc.pdf
 
Set off and carry forward of losses and assessment of individuals.pptx
Set off and carry forward of losses and assessment of individuals.pptxSet off and carry forward of losses and assessment of individuals.pptx
Set off and carry forward of losses and assessment of individuals.pptx
 
Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...
Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...
Call 8867766396 Satta Matka Dpboss Matka Guessing Satta batta Matka 420 Satta...
 
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdfSearch Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdf
 
Evgen Osmak: Methods of key project parameters estimation: from the shaman-in...
Evgen Osmak: Methods of key project parameters estimation: from the shaman-in...Evgen Osmak: Methods of key project parameters estimation: from the shaman-in...
Evgen Osmak: Methods of key project parameters estimation: from the shaman-in...
 

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