SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Andere mochten auch

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

Andere mochten auch (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
 

Ähnlich wie 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
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
Long Nguyen
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
divzi1913
 
Qtp interview questions
Qtp interview questionsQtp interview questions
Qtp interview questions
Ramu Palanki
 
Qtp interview questions
Qtp interview questionsQtp interview questions
Qtp interview questions
Ramu Palanki
 
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
Nicolas Thon
 

Ähnlich wie 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
 

Mehr von 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
 
#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
 
Три вызова реляционным СУБД и новый 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
 

Mehr von 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
 

Kürzlich hochgeladen

Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Sheetaleventcompany
 
Call Girls Kengeri Satellite Town Just Call 👗 7737669865 👗 Top Class Call Gir...
Call Girls Kengeri Satellite Town Just Call 👗 7737669865 👗 Top Class Call Gir...Call Girls Kengeri Satellite Town Just Call 👗 7737669865 👗 Top Class Call Gir...
Call Girls Kengeri Satellite Town Just Call 👗 7737669865 👗 Top Class Call Gir...
amitlee9823
 
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
lizamodels9
 
Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...
Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...
Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...
Anamikakaur10
 
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
daisycvs
 
Insurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usageInsurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usage
Matteo Carbone
 
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
amitlee9823
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
 
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
dlhescort
 

Kürzlich hochgeladen (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...
 
Business Model Canvas (BMC)- A new venture concept
Business Model Canvas (BMC)-  A new venture conceptBusiness Model Canvas (BMC)-  A new venture concept
Business Model Canvas (BMC)- A new venture concept
 
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
 
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
 
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service AvailableCall Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
 
Call Girls Kengeri Satellite Town Just Call 👗 7737669865 👗 Top Class Call Gir...
Call Girls Kengeri Satellite Town Just Call 👗 7737669865 👗 Top Class Call Gir...Call Girls Kengeri Satellite Town Just Call 👗 7737669865 👗 Top Class Call Gir...
Call Girls Kengeri Satellite Town Just Call 👗 7737669865 👗 Top Class Call Gir...
 
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
 
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
 
Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...
Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...
Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...
 
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRLBAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
 
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
 
Insurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usageInsurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usage
 
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
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
 
Dr. Admir Softic_ presentation_Green Club_ENG.pdf
Dr. Admir Softic_ presentation_Green Club_ENG.pdfDr. Admir Softic_ presentation_Green Club_ENG.pdf
Dr. Admir Softic_ presentation_Green Club_ENG.pdf
 
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
 
Phases of Negotiation .pptx
 Phases of Negotiation .pptx Phases of Negotiation .pptx
Phases of Negotiation .pptx
 
Falcon Invoice Discounting: The best investment platform in india for investors
Falcon Invoice Discounting: The best investment platform in india for investorsFalcon Invoice Discounting: The best investment platform in india for investors
Falcon Invoice Discounting: The best investment platform in india for investors
 
👉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...
 

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