- The document discusses schema-less PostgreSQL, including current and future features like hstore and JSON support
- Hstore was introduced in 2003 and provides a flexible way to store semi-structured data, but has limitations as it only supports key-value pairs
- JSON has become more popular and supports hierarchical data structures, but early implementations in PostgreSQL were slow due to textual storage
- Recent developments include the introduction of binary-stored JSONB in PostgreSQL 9.4, which addresses performance issues by avoiding reparsing and supports indexing
- JSONB outperforms regular JSON for input, access, and search performance on real-world bookmark data, with up to 20x faster access times for getting values by key
2015-12-05 Александр Коротков, Иван Панченко - Слабо-структурированные данные...HappyDev
Появление большого количества NoSQL СУБД обусловлено требованиями современных информационных систем, которым большинство традиционных реляционных баз данных не удовлетворяет. Одним из таких требований является поддержка данных, структура которых заранее не определена. Однако при выборе NoSQL БД ради отсутствия схем данных можно потерять ряд преимуществ, которые дают зрелые SQL-решения, а именно: транзакции, скорость чтения строк из таблиц. PostgreSQL, являющаяся передовой реляционной СУБД, имела поддержку слабо-структурированных данных задолго до появления NoSQL, которая обрела новое дыхание в последнем релизе в виде типа данных jsonb, который не только поддерживает стандарт JSON, но и обладает производительностью, сравнимой или даже превосходящей наиболее популярные NoSQL СУБД.
Jsquery - the jsonb query language with GIN indexing supportAlexander Korotkov
PostgreSQL 9.4 has new jsonb data type, which was designed for efficient work with json data. However, its query language is very limited and supports only a few operators. In this talk we introduce jsquery - the jsonb query language, which is flexible, expandable and has GIN indexing support. Jsquery provides postgres users an ability to talk to json data in an efficient way on par with NoSQL databases. The preliminary prototype was presented at PCGon-2014 and has got a good feedback, so now we want to show to european users the new version of jsquery (with some enhancements), which is compatible with 9.4 release and can be installed as an extension. We'll also discuss current issues of jsquery and possible ways of improvements.
Present and future of Jsonb in PostgreSQL
Json - is an ubiquitous data format, which supported in almost any popular databases. PostgreSQL was the first relational database, which received support of native textual json and very efficient binary jsonb data types. Recently published SQL 2016 standard describes the JSON data type and specifies the functions and operators to work with json in SQL, which greatly simplifies the further development of json support in PostgreSQL. We compare existing features of json/jsonb data types with proposed SQL standard and discuss the ways how we could improve json/jsonb support in PostgreSQL.
PostgreSQL offers to application developers a rich support of json data type, providing known advantages of the json data model with traditional benefits of relational databases, such as declarative query language, rich query processing, transaction management providing ACID safety guarantees. However, current support of json is far from ideal, for example, json is still "foreign" data type to SQL - existed jsquery extension tries to implement their own query language, which is being powerfull, is opaque to Postgres planner and optimizer and not extendable. Extending SQL to support json, without commonly accepted standard, is difficult and perspectiveless task. Recently published SQL 2016 standard describes the JSON data type and specifies the functions and operators to work with json in SQL, which makes clear the direction of future development of json support in PostgreSQL. We present our ideas and prototype of future json data type in PostgreSQL with some further non-standard extensions and improvements in storage requirement and index support.
What's the great thing about a database? Why, it stores data of course! However, one feature that makes a database useful is the different data types that can be stored in it, and the breadth and sophistication of the data types in PostgreSQL is second-to-none, including some novel data types that do not exist in any other database software!
This talk will take an in-depth look at the special data types built right into PostgreSQL version 9.4, including:
* INET types
* UUIDs
* Geometries
* Arrays
* Ranges
* Document-based Data Types:
* Key-value store (hstore)
* JSON (text [JSON] & binary [JSONB])
We will also have some cleverly concocted examples to show how all of these data types can work together harmoniously.
A comparison of different solutions for full-text search in web applications using PostgreSQL and other technology. Presented at the PostgreSQL Conference West, in Seattle, October 2009.
2015-12-05 Александр Коротков, Иван Панченко - Слабо-структурированные данные...HappyDev
Появление большого количества NoSQL СУБД обусловлено требованиями современных информационных систем, которым большинство традиционных реляционных баз данных не удовлетворяет. Одним из таких требований является поддержка данных, структура которых заранее не определена. Однако при выборе NoSQL БД ради отсутствия схем данных можно потерять ряд преимуществ, которые дают зрелые SQL-решения, а именно: транзакции, скорость чтения строк из таблиц. PostgreSQL, являющаяся передовой реляционной СУБД, имела поддержку слабо-структурированных данных задолго до появления NoSQL, которая обрела новое дыхание в последнем релизе в виде типа данных jsonb, который не только поддерживает стандарт JSON, но и обладает производительностью, сравнимой или даже превосходящей наиболее популярные NoSQL СУБД.
Jsquery - the jsonb query language with GIN indexing supportAlexander Korotkov
PostgreSQL 9.4 has new jsonb data type, which was designed for efficient work with json data. However, its query language is very limited and supports only a few operators. In this talk we introduce jsquery - the jsonb query language, which is flexible, expandable and has GIN indexing support. Jsquery provides postgres users an ability to talk to json data in an efficient way on par with NoSQL databases. The preliminary prototype was presented at PCGon-2014 and has got a good feedback, so now we want to show to european users the new version of jsquery (with some enhancements), which is compatible with 9.4 release and can be installed as an extension. We'll also discuss current issues of jsquery and possible ways of improvements.
Present and future of Jsonb in PostgreSQL
Json - is an ubiquitous data format, which supported in almost any popular databases. PostgreSQL was the first relational database, which received support of native textual json and very efficient binary jsonb data types. Recently published SQL 2016 standard describes the JSON data type and specifies the functions and operators to work with json in SQL, which greatly simplifies the further development of json support in PostgreSQL. We compare existing features of json/jsonb data types with proposed SQL standard and discuss the ways how we could improve json/jsonb support in PostgreSQL.
PostgreSQL offers to application developers a rich support of json data type, providing known advantages of the json data model with traditional benefits of relational databases, such as declarative query language, rich query processing, transaction management providing ACID safety guarantees. However, current support of json is far from ideal, for example, json is still "foreign" data type to SQL - existed jsquery extension tries to implement their own query language, which is being powerfull, is opaque to Postgres planner and optimizer and not extendable. Extending SQL to support json, without commonly accepted standard, is difficult and perspectiveless task. Recently published SQL 2016 standard describes the JSON data type and specifies the functions and operators to work with json in SQL, which makes clear the direction of future development of json support in PostgreSQL. We present our ideas and prototype of future json data type in PostgreSQL with some further non-standard extensions and improvements in storage requirement and index support.
What's the great thing about a database? Why, it stores data of course! However, one feature that makes a database useful is the different data types that can be stored in it, and the breadth and sophistication of the data types in PostgreSQL is second-to-none, including some novel data types that do not exist in any other database software!
This talk will take an in-depth look at the special data types built right into PostgreSQL version 9.4, including:
* INET types
* UUIDs
* Geometries
* Arrays
* Ranges
* Document-based Data Types:
* Key-value store (hstore)
* JSON (text [JSON] & binary [JSONB])
We will also have some cleverly concocted examples to show how all of these data types can work together harmoniously.
A comparison of different solutions for full-text search in web applications using PostgreSQL and other technology. Presented at the PostgreSQL Conference West, in Seattle, October 2009.
Новые возможности полнотекстового поиска в PostgreSQL / Олег Бартунов (Postgr...Ontico
Я расскажу про новые возможности полнотекстового поиска, которые вошли в последний релиз PostgreSQL - поддержку фразового поиска и набор функций для манипулирования полнотекстовым типом данных (tsvector). Помимо этого, мы улучшили поддержку морфологических словарей, что привело к значительному увеличению числа поддерживаемых языков, оптимизировали работу со словарями, разработали новый индексный метод доступа RUM, который значительно ускорил выполнение ряда запросов с полнотекстовыми операторами.
As your data grows, the need to establish proper indexes becomes critical to performance. MongoDB supports a wide range of indexing options to enable fast querying of your data, but what are the right strategies for your application?
In this talk we’ll cover how indexing works, the various indexing options, and use cases where each can be useful. We'll dive into common pitfalls using real-world examples to ensure that you're ready for scale.
Video available here: http://vivu.tv/portal/archive.jsp?flow=783-586-4282&id=1270584002677
We all know that MongoDB is one of the most flexible and feature-rich databases available. In this webinar we'll discuss how you can leverage this feature set and maintain high performance with your project's massive data sets and high loads. We'll cover how indexes can be designed to optimize the performance of MongoDB. We'll also discuss tips for diagnosing and fixing performance issues should they arise.
There are number of players that provide full text search feature, starting from embedded search to dedicated search servers [solr, sphinx, elasticsearch etc], but setting up and configuring them is a time consuming process and requires considerable knowledge of the tools.
What if we could get comparable search results using full text search capabilities of Postgres. Developers already have the working knowledge of the database, so this should come natural. In addition to that, it will be one less tool to manage.
Code: https://github.com/Syerram/postgres_search
I inherited a MongoDB database server with 60 collections and 100 or so indexes.
The business users are complaining about slow report completion times. What can I do to improve performance?
Cassandra 3.0 - JSON at scale - StampedeCon 2015StampedeCon
This session will explore the new features in Cassandra 3.0, starting with JSON support. Cassandra now allows storing JSON directly to Cassandra rows and vice versa, making it trivial to deploy Cassandra as a component in modern service-oriented architectures.
Cassandra 3.0 also delivers other enhancements to developer productivity: user defined functions let developers deploy custom application logic server side with any language conforming to the Java scripting API, including Javascript. Global indexes allow scaling indexed queries linearly with the size of the cluster, a first for open-source NoSQL databases.
Finally, we will cover the performance improvements in Cassandra 3.0 as well.
Working with JSON Data in PostgreSQL vs. MongoDBScaleGrid.io
In this post, we are going to show you tips and techniques on how to effectively store and index JSON data in PostgreSQL vs. MongoDB. Learn more in the blog post: https://scalegrid.io/blog/using-jsonb-in-postgresql-how-to-effectively-store-index-json-data-in-postgresql
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial IndexesMongoDB
This is the fourth webinar of a Back to Basics series that will introduce you to the MongoDB database. This webinar will introduce you to the aggregation framework.
At Ullink, our java heap are usually pretty large (up to 256GB) and we are dealing with large volume of data. But most of the space consumed in the heap are not business data as we may intuitively think, it is data structures!
In this presentation I would like to show you what are the cost of java objects, and the usual suspects in our data structures (Lists, Maps, Strings) and what we can do about this.
PG Day'14 Russia, Работа со слабо-структурированными данными в PostgreSQL, Ол...pgdayrussia
Доклад был представлен на официальной российской конференции PG Day'14 Russia, посвященной вопросам разработки и эксплуатации PostgreSQL.
<сарказм> MongoDB правит бал в мире слабо-структурированных данных. Привлеченные в MongoDB инвестиции часто затмевают разум (особенно начинающих и доверчивых) разработчиков, которые с радостью бросаются в океан возможностей, предоставляемых NoSQL (это же круто!). Энтузиазм затихает после осознания того факта, что бесплатно ничего не бывает и надо писать своими руками то, что десятилетиями хорошо работает в традиционных реляционных базах данных, которые прекрасно справляются с нагрузками и данными 99% проектов, и ваш проект не входит в оставшийся один процент. </сарказм>
Мир баз данных за последние годы существенно изменился. Всеместное проникновение Интернет-технологий привело к необходимости работы с большим количеством разнородных данных в реальном времени, к чему традиционные реляционные СУБД оказались не готовы. Принято считать, что слабая масштабируемость и излишняя “жесткость” модели данных реляционных СУБД и являются основными причинами появляния и роста популярности NoSQL баз данных (далее, NoSQL).
В докладе мы остановимся на концептуальных предпосылках появления NoSQL и их классификации. Одним из “жупелов” NoSQL является поддержка типа данных JSON, который реализует документо-ориентированную модель данных. Документо-ориентированная модель данных является более гибкой и позволяет менять схему данных “на лету”, что сделать очень трудно в реляционных СУБД, особенно в системах, работающих под большой нагрузкой. Несмотря на успех NoSQL (активно распиаренный использованием в некоторых популярных Интернет-проектах), многие пользователи не готовы приносить в жертву целостность данных в угоду масштабируемости, но хотят иметь гибкость схемы данных в проверенных и надежных реляционных СУБД.
Нами была предложена и реализована поддержка документо-ориентированной модели в PostgreSQL (версия 9.4). Уже более 10 лет в PostgreSQL существует возможность работать со schema-less данными, используя наш модуль расширения hstore. Hstore предлагает хранилище вида "ключ-значение" с сохранением всех реляционных возможностей, что сделало его самым используемым
Новые возможности полнотекстового поиска в PostgreSQL / Олег Бартунов (Postgr...Ontico
Я расскажу про новые возможности полнотекстового поиска, которые вошли в последний релиз PostgreSQL - поддержку фразового поиска и набор функций для манипулирования полнотекстовым типом данных (tsvector). Помимо этого, мы улучшили поддержку морфологических словарей, что привело к значительному увеличению числа поддерживаемых языков, оптимизировали работу со словарями, разработали новый индексный метод доступа RUM, который значительно ускорил выполнение ряда запросов с полнотекстовыми операторами.
As your data grows, the need to establish proper indexes becomes critical to performance. MongoDB supports a wide range of indexing options to enable fast querying of your data, but what are the right strategies for your application?
In this talk we’ll cover how indexing works, the various indexing options, and use cases where each can be useful. We'll dive into common pitfalls using real-world examples to ensure that you're ready for scale.
Video available here: http://vivu.tv/portal/archive.jsp?flow=783-586-4282&id=1270584002677
We all know that MongoDB is one of the most flexible and feature-rich databases available. In this webinar we'll discuss how you can leverage this feature set and maintain high performance with your project's massive data sets and high loads. We'll cover how indexes can be designed to optimize the performance of MongoDB. We'll also discuss tips for diagnosing and fixing performance issues should they arise.
There are number of players that provide full text search feature, starting from embedded search to dedicated search servers [solr, sphinx, elasticsearch etc], but setting up and configuring them is a time consuming process and requires considerable knowledge of the tools.
What if we could get comparable search results using full text search capabilities of Postgres. Developers already have the working knowledge of the database, so this should come natural. In addition to that, it will be one less tool to manage.
Code: https://github.com/Syerram/postgres_search
I inherited a MongoDB database server with 60 collections and 100 or so indexes.
The business users are complaining about slow report completion times. What can I do to improve performance?
Cassandra 3.0 - JSON at scale - StampedeCon 2015StampedeCon
This session will explore the new features in Cassandra 3.0, starting with JSON support. Cassandra now allows storing JSON directly to Cassandra rows and vice versa, making it trivial to deploy Cassandra as a component in modern service-oriented architectures.
Cassandra 3.0 also delivers other enhancements to developer productivity: user defined functions let developers deploy custom application logic server side with any language conforming to the Java scripting API, including Javascript. Global indexes allow scaling indexed queries linearly with the size of the cluster, a first for open-source NoSQL databases.
Finally, we will cover the performance improvements in Cassandra 3.0 as well.
Working with JSON Data in PostgreSQL vs. MongoDBScaleGrid.io
In this post, we are going to show you tips and techniques on how to effectively store and index JSON data in PostgreSQL vs. MongoDB. Learn more in the blog post: https://scalegrid.io/blog/using-jsonb-in-postgresql-how-to-effectively-store-index-json-data-in-postgresql
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial IndexesMongoDB
This is the fourth webinar of a Back to Basics series that will introduce you to the MongoDB database. This webinar will introduce you to the aggregation framework.
At Ullink, our java heap are usually pretty large (up to 256GB) and we are dealing with large volume of data. But most of the space consumed in the heap are not business data as we may intuitively think, it is data structures!
In this presentation I would like to show you what are the cost of java objects, and the usual suspects in our data structures (Lists, Maps, Strings) and what we can do about this.
PG Day'14 Russia, Работа со слабо-структурированными данными в PostgreSQL, Ол...pgdayrussia
Доклад был представлен на официальной российской конференции PG Day'14 Russia, посвященной вопросам разработки и эксплуатации PostgreSQL.
<сарказм> MongoDB правит бал в мире слабо-структурированных данных. Привлеченные в MongoDB инвестиции часто затмевают разум (особенно начинающих и доверчивых) разработчиков, которые с радостью бросаются в океан возможностей, предоставляемых NoSQL (это же круто!). Энтузиазм затихает после осознания того факта, что бесплатно ничего не бывает и надо писать своими руками то, что десятилетиями хорошо работает в традиционных реляционных базах данных, которые прекрасно справляются с нагрузками и данными 99% проектов, и ваш проект не входит в оставшийся один процент. </сарказм>
Мир баз данных за последние годы существенно изменился. Всеместное проникновение Интернет-технологий привело к необходимости работы с большим количеством разнородных данных в реальном времени, к чему традиционные реляционные СУБД оказались не готовы. Принято считать, что слабая масштабируемость и излишняя “жесткость” модели данных реляционных СУБД и являются основными причинами появляния и роста популярности NoSQL баз данных (далее, NoSQL).
В докладе мы остановимся на концептуальных предпосылках появления NoSQL и их классификации. Одним из “жупелов” NoSQL является поддержка типа данных JSON, который реализует документо-ориентированную модель данных. Документо-ориентированная модель данных является более гибкой и позволяет менять схему данных “на лету”, что сделать очень трудно в реляционных СУБД, особенно в системах, работающих под большой нагрузкой. Несмотря на успех NoSQL (активно распиаренный использованием в некоторых популярных Интернет-проектах), многие пользователи не готовы приносить в жертву целостность данных в угоду масштабируемости, но хотят иметь гибкость схемы данных в проверенных и надежных реляционных СУБД.
Нами была предложена и реализована поддержка документо-ориентированной модели в PostgreSQL (версия 9.4). Уже более 10 лет в PostgreSQL существует возможность работать со schema-less данными, используя наш модуль расширения hstore. Hstore предлагает хранилище вида "ключ-значение" с сохранением всех реляционных возможностей, что сделало его самым используемым
Postgres vs Mongo / Олег Бартунов (Postgres Professional)Ontico
РИТ++ 2017, Backend Conf
Зал Конгресс-холл, 6 июня, 17:00
Тезисы:
http://backendconf.ru/2017/abstracts/2781.html
Я хочу немного порушить стереотипы, что Postgres - это чисто реляционная СУБД из прошлого века, плохо приспособленная под реалии современных проектов. Недавно мы прогнали YCSB для последних версий Postgres и Mongodb и увидели их плюсы и минусы на разных типах нагрузки, о которых я буду рассказывать. ...
Hadoop Summit 2014: Query Optimization and JIT-based Vectorized Execution in ...Gruter
Apache Tajo is an open source big data warehouse system on Hadoop. This slide shows two high-tech efforts for performance improvement in Tajo project. First one is query optimization including cost-based join order and progressive optimization. The second effort is JIT-based vectorized processing.
SQL Server 2014 Memory Optimised Tables - AdvancedTony Rogerson
Hekaton is large piece of kit, this session will focus on the internals of how in-memory tables and native stored procedures work and interact – Database structure: use of File Stream, backup/restore considerations in HA and DR as well as Database Durability, in-memory table make up: hash and range indexes, row chains, Multi-Version Concurrency Control (MVCC). Design considerations and gottcha’s to watch out for.
The session will be demo led.
Note: the session will assume the basics of Hekaton are known, so it is recommended you attend the Basics session.
MariaDB Server 10.3 is a culmination of features from MariaDB Server 10.2+10.1+10.0+5.5+5.3+5.2+5.1 as well as a base branch from MySQL 5.5 and backports from MySQL 5.6/5.7. It has many new features, like a GA-ready sharding engine (SPIDER), MyRocks, as well as some Oracle compatibility, system versioned tables and a whole lot more.
Webscale PostgreSQL - JSONB and Horizontal Scaling StrategiesJonathan Katz
All data is relational and can be represented through relational algebra, right? Perhaps, but there are other ways to represent data, and the PostgreSQL team continues to work on making it easier and more efficient to do so!
With the upcoming 9.4 release, PostgreSQL is introducing the "JSONB" data type which allows for fast, compressed, storage of JSON formatted data, and for quick retrieval. And JSONB comes with all the benefits of PostgreSQL, like its data durability, MVCC, and of course, access to all the other data types and features in PostgreSQL.
How fast is JSONB? How do we access data stored with this type? What can it do with the rest of PostgreSQL? What can't it do? How can we leverage this new data type and make PostgreSQL scale horizontally? Follow along with our presentation as we try to answer these questions.
The latest version of my PostgreSQL introduction for IL-TechTalks, a free service to introduce the Israeli hi-tech community to new and interesting technologies. In this talk, I describe the history and licensing of PostgreSQL, its built-in capabilities, and some of the new things that were added in the 9.1 and 9.2 releases which make it an attractive option for many applications.
This is a talk that I gave on July 20, 2012 at the Southern California Python Interest Group meetup at Cross Campus, with food and drinks provided by Graph Effect.
This talk gives an overview of Apache Drill architecture and describes specific features that enable it to get the best performance over NoSQL databases and distributed file systems. It discusses secondary index planning and execution for NoSQL databases and partition pruning and Parquet filter pushdown for distributed file systems.
PostgreSQL - It's kind've a nifty databaseBarry Jones
This presentation was given to a company that makes software for churches that is considering a migration from SQL Server to PostgreSQL. It was designed to give a broad overview of features in PostgreSQL with an emphasis on full-text search, various datatypes like hstore, array, xml, json as well as custom datatypes, TOAST compression and a taste of other interesting features worth following up on.
Amazon DynamoDB is a fully managed, highly scalable NoSQL database service. We will deep dive into how DynamoDB scaling and partitioning works, how to do data modeling based on access patterns using primitives such as hash/range keys, secondary indexes, conditional writes and query filters. We will also discuss how to use DynamoDB Streams to build cross-region replication and integrate with other services (such as Amazon S3, Amazon CloudSearch, Amazon ElastiCache, Amazon Redshift) to enable logging, search, analytics and caching. You will learn design patterns and best practices on how to use DynamoDB to build highly scalable applications, with the right performance characteristics at the right cost.
Similar to Типы данных JSONb, соответствующие индексы и модуль jsquery – Олег Бартунов, Александр Коротков (20)
Предсказание оттока игроков из World of TanksYandex
Одна из наиболее часто возникающих задач в бизнес-аналитике для компаний — это предсказание оттока клиентов. Ведь если заранее знать, что клиент собирается уйти к конкуренту, его можно попытаться остановить. Задача будет рассмотрена на примере прогнозирования оттока игроков из World of Tanks.
Как принять/организовать работу по поисковой оптимизации сайта, Сергей Царик,...Yandex
Лекция Сергея Царика в Школе вебмастеров: «Как принять/организовать работу по поисковой оптимизации сайта».
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
Основные этапы и методы поисковой оптимизации
Рассмотрим проработку стратегии продвижения, планирование ресурсов на проект, поймем как нужно прорабатывать семантическое ядро для продвижения, разберемся с очередностью всех работ.
Разложим по полочкам основные приемы оптимизации в связке с внутренними и внешними факторами ранжирования поисковых систем, а также в связке с поведенческими факторами и характеристиками. Разберемся с тем, что же должен делать оптимизатор для достижения топа.
Что должно включать в себя ТЗ на поисковую оптимизацию
Разберемся с основными блоками технического задания от оптимизатора, с тем, каким оно должно быть с точки зрения подачи информации и ее глубины.
Сравнение in-house подхода и агентства
Рассмотрим все «за» и «против» оптимизатора в штате компании и вне её.
На основе каких метрик нужно оценивать эффективность оптимизаторской работы
Выделим ключевые показатели эффективности работы оптимизатора, рассмотрим процесс их измерения, динамику, разберемся с возможными «миксами» и их связкой с мотивацией подрядчика.
Структурированные данные, Юлия Тихоход, лекция в Школе вебмастеров ЯндексаYandex
Лекция Юлия Тихоход в Школе вебмастеров: «Структурированные данные на поиске»
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
Что такое микроразметка и в чём её польза
Что такое микроразметка (семантическая разметка, семантическая микроразметка) и кому она нужна. Очень кратко — всё, что я знаю о применении семантической разметки поисковыми системами и другими веб-сервисами.
Передача данных в машиночитаемом виде
Какие ещё есть способы передать данные о сайте поисковым системам кроме микроразметки, особенности разных способов. Что бывает с плохими вебмастерами, которые пытаются обмануть поисковые системы и передать неверные данные.
Типы разметки
Из чего состоит микроразметка, какие бывают словари и синтаксисы. Популярные сочетания словарей и синтаксисов, как правильно выбирать нужную комбинацию для своего сайта.
Передача данных об интернет-магазине
Разбор семантической разметки: что в принципе доступно для разметки в интернет-магазине, что это даёт, а что можно не размечать вовсе.
Проверка правильности микроразаметки
Ошибки в микроразметке, способы их обнаружения и исправления. Популярные валидаторы микроразметки. Какие ошибки непременно нужно исправлять, а что можно игнорировать.
Представление сайта в поиске, Сергей Лысенко, лекция в Школе вебмастеров ЯндексаYandex
Лекция Сергея Лысенко в Школе вебмастеров: «Представление сайта в поиске»
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
Основные элементы сниппетов: как влиять на их формирование
Как по внешнему виду и содержанию визитки судят, стоит ли «связываться», так и по представлению сайта на странице выдачи пользователи решают, стоит ли переходить на сайт. Как изменить представление сайта в выдаче поисковых систем? Что может повлиять на CTR и что для этого нужно сделать? Рассмотрим фавиконки, навигационные цепочки, быстрые ссылки и многое, многое другое.
Зачем нам заголовок: как им управлять
Что должно быть в заголовке, а чего уж точно не стоит делать. Как избавиться от мусора и расставить акценты. И как это скажется на представлении сайта в поиске.
Основной контент аннотации и мета-описания: что нам они дают
Сниппет — зачем он нужен? Как обрабатываются данные для аннотаций? Что в сниппете помогает, а что мешает пользователю сориентироваться? Как подсказать поисковой системе, что выводить в сниппете? От Open Graf до schema.org. Инструменты, возможности, рекомендации.
Плохие методы продвижения сайта, Екатерины Гладких, лекция в Школе вебмастеро...Yandex
Лекция Екатерины Гладких в Школе вебмастеров: «Плохие методы продвижения сайта»
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
Как завязывают с портянками
Как использовать wordstat, чтобы превратить текст в SEO-портянку. Как Яндекс определяет текстовый спам и какие ограничения могут быть применены к сайтам, злоупотребляющим ключевыми словами.
Эффектное размещение SEO-ссылок
Какие бывают SEO-ссылки и как они классифицируются в базе Яндекса. В чём отличие SEO-ссылок от рекламы. Как размещать SEO-ссылки наиболее эффектно. Методы борьбы против ссылочного спама – АГС и Минусинск. Снятие ссылок.
Поведенческие факторы, медитативные практики
Популярные сервисы накрутки: как это работает и как это не работает. Методы накрутки и методы борьбы с мошенничеством. Примеры пользовательских сессий и кто на самом деле посещает ваш сайт. Как выйти из-под санкций за накрутку поведенческих факторов.
Основные принципы ранжирования, Сергей Царик и Антон Роменский, лекция в Школ...Yandex
Лекция Сергея Царика и Антона Роменского в Школе вебмастеров: «Основные принципы ранжирования»
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
Как работает поиск
При запросе пользователя к поисковой системе происходит множество процессов, которые позволяют дать наиболее релевантный ответ. Рассмотрим основные механизмы формирования выдачи: формулы, Матрикснет, персонализацию и обновления.
Что учитывается при ранжировании сайтов
Так как сайты разные и по-разному решают пользовательские задачи, при ранжировании поисковой системе нужно учитывать множество факторов. Поговорим о том, что обязательно должно быть на сайте для правильной индексации.
Ещё о факторах ранжирования
Какой контент действительно важен и как его правильно представить. Для правильного ранжирования сайта важно разобраться с его региональной привязкой. Разберёмся, какой регион присваивать сайту и как сделать это правильно.
Реальный кейс долгосрочной работы над позициями
Посмотрим на реальном примере, как изменялись основные жизненные характеристики (трафик, конверсии) сайта на пути в топ выдачи поисковых систем.
Основные принципы индексирования сайта, Александр Смирнов, лекция в Школе веб...Yandex
Лекция Александра Смирнова в Школе вебмастеров: «Основные принципы индексирования сайта».
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
Как поиск находит страницу, её путь до появления в поиске
Поисковые системы постоянно собирают информацию о страницах в интернете. Как же это происходит и как добавить страницы своего сайта в поиск? Проверка индексирования сайта.
Как управлять роботом (зеркала, sitemap, robots.txt)
Множество сайтов в интернете доступны сразу по нескольким адресам. Как указать поисковому роботу на основной и как скорректировать индексирование?
Особенности индексирования
Современные сайты используют различные технологии в своей работе. Рассмотрим, как настроить их правильно и сделать контент доступным для робота.
Как улучшить индексирование (дубли, HTTP-ответ, удаление из поиска)
В поиск попадают различные страницы, которые известны роботу. Какие нужны, а какие нет? Как повлиять на их индексирование?
Мобильное приложение: как и зачем, Александр Лукин, лекция в Школе вебмастеро...Yandex
Лекция Александра Лукина в Школе вебмастеров: «Мобильное приложение: как и зачем»
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
Проектирование. Быть или не быть
Обсудим обоснование для разработки мобильного приложения — какую ценность оно может принести для проекта и бизнеса. Определим основные типы приложений и сценарии использования. Рассмотрим основные технологии и выбор оптимальных для конкретных задач. ТЗ — как оценить и какие особенности необходимо учесть.
Разработка. Важные детали
На что обратить внимание на этапе разработки и тестирования, заметки по специфике мобильных экосистем. Выбираем арсенал SDK для всестороннего анализа проекта в полёте.
Публикация и продвижение
Кратко рассмотрим специфику Google Play и AppStore. Проведём экскурс в мир мобильного маркетинга, подчеркнём сходства с вебом и отличия от него. Рассмотрим ключевые метрики для анализа продукта и процесса продвижения, а также способы их повышения.
Сайты на мобильных устройствах, Олег Ножичкин, лекция в Школе вебмастеров Янд...Yandex
Лекция Олега Ножичкина в Школе вебмастеров: «Сайты на мобильных устройствах»
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
Статистика и тренды по мобильному интернету
Основные показатели мобильного интернет-рынка. Тенденции роста мобильной аудитории.
Новые алгоритмы ранжирования поисковых систем
Адаптация сайта к мобильным пользователям и её влияние на позиции в поисковой выдаче.
Возможности для бизнеса в мобильном вебе
Мобильный сайт позволяет воспользоваться дополнительными возможностями взаимодействия с пользователем. Рассмотрим конкретные примеры.
Мобильный сайт и приложение — в чём разница
Чем отличается мобильное приложение от мобильно сайта. Какие преимущества и недостатки у каждого варианта.
Представление сайтов на мобильных устройствах
Адаптивные сайты. Мобильные сайты. Сайты для десктопа. Чем они отличаются, какие преимущества у каждого типа и нужно ли переключаться между мобильной и десктоп-версиями?
Удобный мобильный сайт для пользователя
Поведение пользователей на мобильном сайте. Отличия от десктопа, достижение целей и простые правила увеличения конверсии.
Специфика разработки мобильного сайта
Особенности проектирования, разработки и тестирования сайтов.
Инструменты для разработки мобильных сайтов
Готовые инструменты для проектирования и тестирования. Примеры фреймворков.
Качественная аналитика сайта, Юрий Батиевский, лекция в Школе вебмастеров Янд...Yandex
Лекция Юрия Батиевского в Школе вебмастеров: «Качественная аналитика сайта»
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
Что мы хотим от аналитики сайта
На какие вопросы должна отвечать аналитика сайта. Как аналитика сайта связана с аналитикой бизнеса. На какие блоки можно поделить аналитику онлайн-процессов. Какой должна быть идеальная аналитическая система.
Анализ общих показателей бизнеса
Как построить систему аналитики бизнеса в интернете. Ключевые показатели эффективности (KPI). Построение воронки продаж. Business Intelligence — сквозная аналитика всех процессов.
Обзор инструментов для анализа сайта и аудитории
Яндекс.Метрика и Google Analytics как основа веб-аналитики. Инструменты для веб-мастеров. Инструменты для анализа действий пользователей (Kiss-metrics, Woopra, Mixpanel). Системы для подсчета целевых действий, CPA и ROMI.
Анализ каналов привлечения клиентов
Как анализировать источники трафика. Популярные инструменты для анализа.
Пройти тест по теме
Процесс развертывания системы аналитики сайта
Подготовка к установке систем веб-аналитики. Тонкости установки и настройки трекеров. Подключение коллтрекинга и дополнительных инструментов фиксации целевых действий. Настройка пользовательских сценариев. Пример по анализу пользовательского сценария.
Что можно и что нужно измерять на сайте, Петр Аброськин, лекция в Школе вебма...Yandex
Лекция Петра Аброськина в Школе вебмастеров: «Что можно и что нужно измерять на сайте».
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
Базовые принципы веб-аналитики
Как работает веб-аналитика и какие подводные камни есть в учёте и анализе данных. Как правильно работать с данными.
Основные метрики и термины
Посетители, визиты, глубина просмотра, время на сайте — какие метрики важны и чем они отличаются.
Как выбрать правильный KPI
Самый важный этап в веб-аналитике и продвижении сайта. Какие цели выбрать интернет-магазину, сайту услуг, контентному проекту и т.д.
Ключевые группы отчетов и применение знаний на практике
Семь главных типов отчётов для бизнеса. Анализ контекстной рекламы, SEO и контента сайта — на конкретных примерах.
Как правильно поставить ТЗ на создание сайта, Алексей Бородкин, лекция в Школ...Yandex
Лекция Алексея Бородкина в Школе вебмастеров: «Как правильно поставить ТЗ на создание сайта».
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
ТЗ: две буквы с большим потенциалом
Что такое техническое задание. Какое место оно занимает в веб-разработке. Какие цели преследует. И каким требованиям оно должно отвечать.
Что нужно сделать, прежде чем садиться за ТЗ
Зачем нужна подготовка к написанию ТЗ. Какую информацию нужно собрать и как выстроить этот процесс. На каком этапе веб-разработки нужно писать ТЗ — и что будет, если этот момент упустить. Какое отношение имеют к ТЗ прототипы, пользовательские истории и прочие инструменты проектирования.
Хорошее ТЗ
Как соединить в один документ описание интерфейсов, структуру данных и много чего ещё. Структура правильного, хорошего ТЗ с подробным разбором каждого пункта. С какой стороны приступать и как эффективнее всего выстроить работу.
Кто должен писать ТЗ
Кто может написать хорошее ТЗ. Где найти такого человека и как встроить его в общие процессы. Что делать, если ТЗ пишет сам заказчик.
Плохое ТЗ
Популярные ошибки. Чем они ужасны и как их избежать.
Жизнь с ТЗ
По какой схеме нужно согласовывать ТЗ. Как применять его в дальнейшей работе. Кому не нужно показывать ТЗ ни при каких обстоятельствах. Что делать, если ТЗ никому не нравится.
ТЗ по ГОСТ: ад на Земле
Краткая история развития ТЗ со времён Брежнева и до наших дней. Почему я старательно избегаю слова «ТЗ». Почему вы должны нервно вздрагивать при слове «ГОСТ». Что делать, если вы работаете с госзаказчиком.
Как защитить свой сайт, Пётр Волков, лекция в Школе вебмастеровYandex
Лекция Петра Волкова в Школе вебмастеров: «Как защитить свой сайт».
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
Актуальные типы угроз и динамика их развития
Компрометация сервера и её последствия. Распределённые атаки типа «отказ в обслуживании». Подмена или добавление рекламы на стороне клиента. Атаки, направленные на пользователей. Проблемы, связанные со внешним содержимым.
Управление рисками безопасности веб-сайтов
Разные типы сайтов подвержены разным типам рисков информационной безопасности. Понимание целей и подходов злоумылшенников как ключ к эффективному снижению рисков. Методы монетизации атак на сайты.
Доступный инструментарий и методики для обеспечения безопасности
Открытые инструменты форензики для типовых и сложных проектов. Системы обнаружения вторжений, подходы к проектированию безопасности в архитектуре и процессах.
Как правильно составить структуру сайта, Дмитрий Сатин, лекция в Школе вебмас...Yandex
Лекция Дмитрия Сатина в Школе вебмастеров: «Как правильно составить структуру сайта».
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
Структура сайта, ориентированная на человека; построение структуры, карточная сортировка
Содержимое сайтов часто организовано так, как кажется удобным разработчику или контент-менеджеру компании. Чаще всего такие структуры неудобны для реальных посетителей, потому что не совпадают с их знаниями, не поясняют, как устроен материал, и не помогают найти желаемое. Структура, ориентированная на пользователя, повышает вероятность того, что посетители найдут нужную информацию или товар и сделают это быстро.
Стройте структуру, исходя из пользовательских сценариев. Выделение на сайте разделов, соответствующих структуре компании или схеме процесса закупки, как правило, усложняет навигацию для пользователя. Правильная структура учитывает уровень знаний покупателя и использует понятные ему термины и способы группировки.
Разные типы структур, средства навигации, дальнейший поиск информации на странице
Структуры сайтов, на которых ищут что-то определённое, отличаются от тех, что используются на сайтах, посетители которых ещё не уверены, что именно они хотят или как называется нужная вещь. Строгие структуры — например, организация по наименованию товара, производителю, — предполагают один способ группировки. При нестрогой организации данные можно группировать по теме, по жизненной ситуации и так далее. Используйте средства навигации, которые помогают понять, как организован материал. Решая, какой будет визуальная реализация навигации на сайте, необходимо учитывать количество разделов и связи �
Технические особенности создания сайта, Дмитрий Васильева, лекция в Школе веб...Yandex
Лекция Дмитрия Васильева в Школе вебмастеров: «Технические особенности создания сайта».
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
Сайт — расплывчатое понятие
Раньше под словом «сайт» понимался набор HTML-страниц, расположенных в домене второго или третьего уровня. Появление социальных сетей размыло это понятие.
Как выбрать домен
Различные варианты, и какой из них подойдёт именно вашему сайту: доменные зоны, читаемые и нечитаемые домены, кириллица и латиница.
Подходы к созданию сайтов
Первые сайты делались на чистом HTML. Сейчас такой способ ещё встречается, но подавляющее большинство веб-страниц создаются при помощи CMS, фреймворков, конструкторов.
Составные сущности: структура, макеты дизайна, интерактивные элементы, контент, система прав. Размещение сайта на хостинге. Российские и зарубежные, дорогие и дешевые, облачные и традиционные провайдеры. Кратко о тонкостях взаимодействия с ними.
Что такое HTTPS
Всё более популярный безопасный протокол доступа к сайту. Нужен ли он вам и в каких случаях. Как выбрать платформу для сайта, основные системы управления сайтом (CMS) и конструкторы.
Сайт после запуска
Сайты создаются с конкретной целью, обычно связанной с получением дохода. Как контент сайта и его технические характеристики напрямую могут влиять на бизнес-эффективность.
Конструкторы для отдельных элементов сайта, Елена Першина, лекция в Школе веб...Yandex
Лекция Елены Першиной в Школе вебмастеров: «Конструкторы для отдельных элементов сайта».
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
О пользе тех или иных технологий
Взгляд в будущее, короткий обзор других полезных технологий и «опасностей», которые подстерегают на пути к правильному их выбору.
Как выбрать поиск для сайта
Поиск для сайта — важный инструмент навигации. Чтобы оценить качество поиска по своему сайту, посмотрите на количество уходов со страницы результатов. Полнота, скорость индексирования, обработка запросов (исправление ошибок, опечаток, неправильной раскладки) — без этого невозможно представить качественный поиск.
Как выбрать карты для сайта
Уход посетителя с сайта на «большие» Яндекс.Карты за точной информацией об организации может обернуться потерей клиента, который уже был готов к покупке. Чтобы этого не допустить, лучше сделать интерактивную карту прямо на сайте.
Автоматизация оплаты на сайте
Люди привыкают платить картой, сегодня даже уличные киоски принимают их. Поэтому многим посетителям кажется «подозрительным» интернет-магазин, в котором недоступны электронные платежи. Начать приём банковских карт в онлайне очень просто, главное выбрать для этого подходящую технологию.
Перевод важных страниц
На каких языках говорит ваша аудитория, много ли у вас посетителей из-за рубежа? Ответы на эти вопросы даст Яндекс.Метрика. Именно она поможет оценить, нужно ли тратиться на профессионального переводчика и готовить отдельные описания товаров или новости на других языках. Во многих случаях для совершения покупки достаточно и простого машинного перевода. Узнайте, как его настроить, чтобы ключевые разделы сайта автоматически переводились для иностранных посетителей.
Социальная интеграция
Как заставить пользователей говорить о себе в социальных сетях? В первую очередь нужно сделать хороший продукт или услугу, но и без удобного инструмента для «шаринга» в соцсетях — никуда. Рекомендации о том, как выбрать и установить такой инструмент к себе на сайт.
Контент для интернет-магазинов, Катерина Ерошина, лекция в Школе вебмастеров ...Yandex
Лекция Катерины Ерошиной в Школе вебмастеров: «Контент для интернет-магазинов».
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
Виды контента для интернет-магазинов
Основные страницы, карточки товаров, каталог в целом. Письма покупателям. Статьи для интернет-магазина.
Основные сервисные страницы: что нужно знать покупателю
О страницах доставки, оплаты, контактов, условий работы.
Страница товара интернет-магазина: какой нужен текст, чтобы товар нашли
Признаки товаров. Сниппеты товарных позиций. Когда текст не нужен вообще. Постоянная и техническая информация на карточке.
Блог и внешние публикации интернет-магазина
О чем писать, чтобы подогреть интерес к магазину. Сторителлинг. UGC: методы вовлечения (кратко).
Персонализация интернет-магазина: стать ближе к покупателю
Красивый пример личного бренда директора магазина.
Копирайтинг для интернет-магазина: на чём можно и нельзя экономить
Что делать, если у вас 100 000 товарных позиций и они постоянно меняются.
Хорошее ТЗ копирайтеру для наполнения интернет-магазина
Что должен знать копирайтер, чтобы не писать ерунду.
Как оценить работу копирайтера
Стандартные проверки. Контроль качества текста средствами аналитики.
Как написать хороший текст для сайта, Катерина Ерошина, лекция в Школе вебмас...Yandex
Лекция Катерины Ерошиной в Школе вебмастеров: «Как написать хороший текст для сайта».
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
Назначение и типы текстов на сайте и вне его
Цель текста — влиять на поведение пользователя. Самое простое — информировать, самое сложное — привести к покупке. Виды текстов для внешних публикаций. Белые книги и другие способы подтвердить экспертизу.
Контент-план для наполнения, развития сайта и внешних публикаций
Как проектировать контент для нового сайта. Как наращивать информационную массу сайта. Внешние контакты с потребителем.
Разные уровни вовлечения: информируем, продаём, помогаем
Пройти по пути покупателя, выдавать информацию, необходимую для совершения следующего шага. Ловушки на этом пути.
Информационный стиль: применение с пониманием
Чистить текст без фанатизма. Эмоциональное вовлечение. Рациональное обоснование.
Структура и вёрстка
Заголовки и подзаголовки, списки, абзацы, иерархия подачи информации.
SEO-аспекты и LSI-копирайтинг
Понимание ценности ключей. Зачем копирайтеру нужно семантическое ядро.
Оценка качества текста (чеклист)
Уникальность, фактическая достоверность, соответствие целям, информационная плотность, грамотность.
Usability и дизайн - как не помешать пользователю, Алексей Иванов, лекция в Ш...Yandex
Лекция Алексея Иванова в Школе вебмастеров: «Usability и дизайн: как не помешать пользователю».
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
Что такое юзабилити и почему оно важно
Поведение пользователей на сайте и достижение ими запланированных целей зависит не только от контента, но и от удобства сайта.
Информационное и функциональное наполнение сайта
Перед созданием сайта нужно правильно определить, какая информация и какой функционал должны быть на сайте. При этом нужно исходить не из того, что у вас есть, а из того, что будет нужно будущим посетителям вашего сайта.
Проектирование входных страниц
В зависимости от целей сайта и источников посетителей нужно сформулировать требования к входным страницам сайта и их содержанию.
Сценарии поведения пользователя
Для правильного распределения информации нужно описать сценарии взаимодействия с сайтом для разных групп посетителей. Рассмотрим методы совмещения разных сценариев на одном сайте.
Пройти тест по теме
Управление конверсией
В большинстве случаев мы ждем от посетителя сайта какого-то целевого действия. Это может быть регистрация, отправка заявки, звонок или что-то ещё. Вы увидите способы мотивации посетителей к совершению целевого действия для различных типов сайтов.
Пройти тест по теме
Основные принципы распределения информации
В рамках этого блока вы увидите, как нужно распределять информацию на странице, чтобы посетители увидели всё, что вы хотите им показать.
Мобильная версия сайта и принципы юзабилити
Всё больше посетителей приходят на сайт с мобильных устройств. Рассмотрим основные особенности взаимодействия с информацией с мобильного устройства и подходы к адаптации сайта под них.
Cайт. Зачем он и каким должен быть, Алексей Иванов, лекция в Школе вебмастеро...Yandex
Лекция Алексея Иванова в Школе вебмастеров Яндекса: «Сайт. Зачем он и каким должен быть».
https://academy.yandex.ru/events/webmasters_school/yawebm2015/
Типы сайтов и потребности аудитории
В зависимости от решаемых задач, сайты можно разделить на несколько характерных типов с разными функциями и контентом. Перед созданием сайта важно понять, чего ждут посетители и какими хотят видеть веб-страницы. При этом на один и тот же сайт может попадать разная аудитория, которая ведёт себя по-разному и каждая имеет свои потребности. Для каждого сегмента нужно разработать отдельные сценарии взаимодействия с информацией на вашей площадке.
Сайт с точки зрения бизнеса
Чаще всего сайт создается для решения конкретных бизнес-задач. Рассмотрим различные типы монетизации сайтов и особенности каждого из них.
Основные показатели и методы измерения
Одно из главных преимуществ цифровых каналов — детальная аналитика взаимодействия посетителей с сайтом. В данном блоке рассмотрим основные инструменты измерения, ключевые показатели сайта, на которые нужно обращать внимание, и подходы к интерпретации полученных данных для принятия решений.
1.Wireless Communication System_Wireless communication is a broad term that i...JeyaPerumal1
Wireless communication involves the transmission of information over a distance without the help of wires, cables or any other forms of electrical conductors.
Wireless communication is a broad term that incorporates all procedures and forms of connecting and communicating between two or more devices using a wireless signal through wireless communication technologies and devices.
Features of Wireless Communication
The evolution of wireless technology has brought many advancements with its effective features.
The transmitted distance can be anywhere between a few meters (for example, a television's remote control) and thousands of kilometers (for example, radio communication).
Wireless communication can be used for cellular telephony, wireless access to the internet, wireless home networking, and so on.
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBrad Spiegel Macon GA
Brad Spiegel Macon GA’s journey exemplifies the profound impact that one individual can have on their community. Through his unwavering dedication to digital inclusion, he’s not only bridging the gap in Macon but also setting an example for others to follow.
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC
Ellisha Heppner, Grant Management Lead, presented an update on APNIC Foundation to the PNG DNS Forum held from 6 to 10 May, 2024 in Port Moresby, Papua New Guinea.
This 7-second Brain Wave Ritual Attracts Money To You.!nirahealhty
Discover the power of a simple 7-second brain wave ritual that can attract wealth and abundance into your life. By tapping into specific brain frequencies, this technique helps you manifest financial success effortlessly. Ready to transform your financial future? Try this powerful ritual and start attracting money today!
Italy Agriculture Equipment Market Outlook to 2027harveenkaur52
Agriculture and Animal Care
Ken Research has an expertise in Agriculture and Animal Care sector and offer vast collection of information related to all major aspects such as Agriculture equipment, Crop Protection, Seed, Agriculture Chemical, Fertilizers, Protected Cultivators, Palm Oil, Hybrid Seed, Animal Feed additives and many more.
Our continuous study and findings in agriculture sector provide better insights to companies dealing with related product and services, government and agriculture associations, researchers and students to well understand the present and expected scenario.
Our Animal care category provides solutions on Animal Healthcare and related products and services, including, animal feed additives, vaccination
3. Alexander Korotkov
• Indexed regexp search
• GIN compression & fast scan
• Fast GiST build
• Range types indexing
• Split for GiST
aekorotkov@gmail.com
4. Agenda
• The problem
• Hstore
• Introduction to jsonb indexing
• Jsquery - Jsonb Query Language
• Exercises on jsonb GIN opclasses with Jsquery support
• VODKA access method
5. The problem
• The world of data and applications is changing
• BIG DATA (Volume of data,Velocity of data in-out, Variety of data)
• Web applications are service-oriented
• Service itself can aggregate data, check consistency of data
• High concurrency, simple queries
• Simple database (key-value) is ok
• Eventual consistency is ok, no ACID overhead
• Application needs faster releases
• NoSQL databases match all of these — scalable, efficient, fault-tolerant,
no rigid schema, ready to accept any data.
6. NoSQL
• Key-value databases
• Ordered k-v for ranges support
• Column family (column-oriented) stores
• Big Table — value has structure:
• column families, columns, and timestamped versions (maps-of maps-of
maps)
• Document databases
• Value has arbitrary structure
• Graph databases — evolution od ordered-kv
7.
8. The problem
• What if application needs ACID and flexibility of NoSQL ?
• Relational databases work with data with schema known in advance
• One of the major compaints to relational databases is rigid schema.
It's not easy to change schema online (ALTER TABLE … ADD COLUMN...)
• Application should wait for schema changing, infrequent releases
• NoSQL uses json format, why not have it in relational database ?
JSON in PostgreSQL
This is the challenge !
9. Challenge to PostgreSQL !
• Full support of semi-stuctured data in PostgreSQL
• Storage
• Operators and functions
• Efficiency (fast access to storage, indexes)
• Integration with CORE (planner, optimiser)
• Actually, PostgreSQL is schema-less database since 2003 — hstore, one
of the most popular extension !
11. Introduction to Hstore
id col1 col2 col3 col4 col5 A lot of columns
key1, …. keyN
● The problem:
● Total number of columns may be very large
● Only several fields are searchable ( used in WHERE)
● Other columns are used only to output
● These columns may not known in advance
● Solution
● New data type (hstore), which consists of (key,value) pairs (a'la perl hash)
12. Introduction to Hstore
id col1 col2 col3 col4 col5 Hstore
key1=>val1, key2=>val2,.....
● Easy to add key=>value pair
● No need change schema, just change hstore.
● Schema-less PostgreSQL in 2003 !
13. Introduction to hstore
• Hstore — key/value binary storage (inspired by perl hash)
'a=>1, b=>2'::hstore
• Key, value — strings
• Get value for a key: hstore -> text
• Operators with indexing support (GiST, GIN)
Check for key: hstore ? text
Contains: hstore @> hstore
• check documentations for more
• Functions for hstore manipulations (akeys, avals, skeys, svals, each,......)
• Hstore provides PostgreSQL schema-less feature !
• Faster releases, no problem with schema upgrade
14. Hstore binary storage
Npairs:31
Key endpos:
31
HEntry array String array
Oleg Bartunov, Teodor Sigaev Nested hstore with array support PGConf.EU, Dublin, Nov 1, 2013
Varlena
header
New version flag:1
Val endpos:
31
ISNULL:1
... key val ...
Start End
First key 0 HEntry[0]
i-th key HEntry[i*2 - 1] HEntry[i*2]
i-th value HEntry[i*2] HEntry[i*2 + 1]
Pairs are lexicographically ordered by key
15. Hstore limitations
Levels: unlimited
Number of elements in array: 2^31
Number of pairs in hash: 2^31
Length of string: 2^31 bytes
2^31 bytes = 2 GB
Oleg Bartunov, Teodor Sigaev Nested hstore with array support PGConf.EU, Dublin, Nov 1, 2013
16. History of hstore development
• May 16, 2003 — first version of hstore
17. History of hstore development
• May 16, 2003 - first (unpublished) version of hstore for PostgreSQL
7.3
• Dec, 05, 2006 - hstore is a part of PostgreSQL 8.2
(thanks, Hubert Depesz Lubaczewski!)
• May 23, 2007 - GIN index for hstore, PostgreSQL 8.3
• Sep, 20, 2010 - Andrew Gierth improved hstore, PostgreSQL 9.0
20. GIN improvements
• GIN in 9.4 is greatly improved
• Posting lists compression (varbyte encoding) — smaller indexes
• 9.3: always 6 bytes (4 bytes blockNumber , 2 bytes offset): 90 bytes
(0,8) (0,14) (0,17) (0,22) (0,26) (0,33) (0,34) (0,35) (0,45) (0,47) (0,48) (1,3) (1,4)
(1,6) (1,8)
• 9.4: 1-6 bytes per each item, deltas from previous item: 21 bytes
(0,8) +6 +3 +5 +4 +7 +1 +1 +10 +2 +1 +2051 +1+2 +2
SELECT g % 10 FROM generate_series(1,10000000) g; 11Mb vs 58Mb
• Fast scan of posting lists - «rare & frequent» queries much faster
• 9.3: read posting lists for «rare» and «frequent» and join them
Time(frequent & rare) ~ Time(frequent)
• 9.4: start from posting list for «rare» and skip «frequent» list if no match
Time(frequent & rare) ~ Time(rare)
21. Hstore is DEAD ? No !
• How hstore benefits by GIN improvement in 9.4 ?
GIN stands for Generalized Inverted Index, so virtually all data types, which
use GIN, get benefit !
• Default hstore GIN opclass considers keys and values separately
• Keys are «frequent», value are «rare»
• Contains query: hstore @> 'key=>value' improved a lot for «rare» values
• Index size is smaller, less io
22. Hstore 9.3 vs 9.4
Total: 7240858 geo records:
"fcode"=>"RFSU",
"point"=>"(8.85,112.53333)",
"fclass"=>"U",
"asciiname"=>"London Reefs",
"elevation"=>NULL,
"geonameid"=>"1879967",
"population"=>"0"
Query:
SELECT count(*) FROM geo
WHERE geo @> 'fcode=>STM';
gin_hstore_ops: index keys and values
gin_hstore_bytea_ops = gin_hstore_ops, no collation comparison
gin_hstore_hash_ops: index hash(key.value)
23. Hstore 9.3 vs 9.4
9.3
|-------------------------+-------+----------+-------+---------|
| Name | Type | Owner | Table | Size |
|-------------------------+-------+----------+-------+---------|
| geo | table | postgres | | 1352 MB |
| geo_hstore_bytea_ops | index | postgres | geo | 1680 MB |
| geo_hstore_hash_ops_idx | index | postgres | geo | 1073 MB |
|-------------------------+-------+----------+-------+---------|
9.4
|-------------------------+-------+----------+-------+---------|
| Name | Type | Owner | Table | Size |
|-------------------------+-------+----------+-------+---------|
| geo | table | postgres | | 1352 MB |
| geo_hstore_bytea_ops | index | postgres | geo | 1296 MB |
| geo_hstore_hash_ops_idx | index | postgres | geo | 925 MB |
|-------------------------+-------+----------+-------+---------|
CREATE OPERATOR CLASS gin_hstore_bytea_ops FOR TYPE hstore
….....................................................................................
FUNCTION 1 byteacmp(bytea,bytea),
….....................................................................................
STORAGE bytea;
CREATE INDEX: 239 s Much faster comparison (no collation)
CREATE OPERATOR CLASS gin_hstore_ops FOR TYPE hstore
….....................................................................................
FUNCTION 1 bttextcmp(text,text),,
….....................................................................................
STORAGE text;
CREATE INDEX: 2870 s
24. Hstore 9.3 vs 9.4
SUMMARY:
● 9.4 GIN posting list compression:
indexes are smaller
● 9.4 GIN is smart regarding 'freq & rare' queries:
time (freq & rare) ~ time (rare) instead of
time (freq & rare) ~ time (freq)
● gin_hstore_hash_ops is good on 9.3 & 9.4 and
faster default gin opclass
● Use gin_hstore_bytea_ops instead of default
gin_hstore_ops — much faster create index
Get hstore_ops from:
from https://github.com/akorotkov/hstore_ops
25. Introduction to hstore
• Hstore benefits
• In provides a flexible model for storing a semi-structured data in relational
database
• hstore has binary storage and rich set of operators and functions, indexes
• Hstore drawbacks
• Too simple model !
Hstore key-value model doesn't supports tree-like structures as json
(introduced in 2006, 3 years after hstore)
• Json — popular and standartized (ECMA-404 The JSON Data
Interchange Standard, JSON RFC-7159)
• Json — PostgreSQL 9.2, textual storage
26. Hstore vs Json
• hstore is faster than json even on simple data
CREATE TABLE hstore_test AS (SELECT
'a=>1, b=>2, c=>3, d=>4, e=>5'::hstore AS v
FROM generate_series(1,1000000));
CREATE TABLE json_test AS (SELECT
'{"a":1, "b":2, "c":3, "d":4, "e":5}'::json AS v
FROM generate_series(1,1000000));
SELECT sum((v->'a')::text::int) FROM json_test;
851.012 ms
SELECT sum((v->'a')::int) FROM hstore_test;
330.027 ms
27. Hstore vs Json
• PostgreSQL already has json since 9.2, which supports document-based
model, but
• It's slow, since it has no binary representation and needs to be parsed every
time
• Hstore is fast, thanks to binary representation and index support
• It's possible to convert hstore to json and vice versa, but current hstore is
limited to key-value
• Need hstore with document-based model. Share it's
binary representation with json !
29. Nested hstore & jsonb
• Nested hstore at PGCon-2013, Ottawa, Canada ( May 24) — thanks
Engine Yard for support !
One step forward true json data type.Nested hstore with arrays support
• Binary storage for nested data at PGCon Europe — 2013, Dublin, Ireland
(Oct 29)
Binary storage for nested data structuresand application to hstore data type
• November, 2013 — binary storage was reworked, nested hstore and
jsonb share the same storage. Andrew Dunstan joined the project.
• January, 2014 - binary storage moved to core
30. Nested hstore & jsonb
• Feb-Mar, 2014 - Peter Geoghegan joined the project, nested hstore
was cancelled in favour to jsonb (Nested hstore patch for 9.3).
• Mar 23, 2014 Andrew Dunstan committed jsonb to 9.4 branch !
pgsql: Introduce jsonb, a structured format for storing json.
Introduce jsonb, a structured format for storing json.
The new format accepts exactly the same data as the json type. However, it is
stored in a format that does not require reparsing the orgiginal text in order
to process it, making it much more suitable for indexing and other operations.
Insignificant whitespace is discarded, and the order of object keys is not
preserved. Neither are duplicate object keys kept - the later value for a given
key is the only one stored.
31. Jsonb vs Json
SELECT '{"c":0, "a":2,"a":1}'::json, '{"c":0, "a":2,"a":1}'::jsonb;
json | jsonb
-----------------------+------------------
{"c":0, "a":2,"a":1} | {"a": 1, "c": 0}
(1 row)
• json: textual storage «as is»
• jsonb: no whitespaces
• jsonb: no duplicate keys, last key win
• jsonb: keys are sorted
32. Jsonb vs Json
• Data
• 1,252,973 Delicious bookmarks
• Server
• MBA, 8 GB RAM, 256 GB SSD
• Test
• Input performance - copy data to table
• Access performance - get value by key
• Search performance contains @> operator
33. Jsonb vs Json
• Data
• 1,252,973 bookmarks from Delicious in json format (js)
• The same bookmarks in jsonb format (jb)
• The same bookmarks as text (tx)
=# dt+
List of relations
Schema | Name | Type | Owner | Size | Description
--------+------+-------+----------+---------+-------------
public | jb | table | postgres | 1374 MB | overhead is < 4%
public | js | table | postgres | 1322 MB |
public | tx | table | postgres | 1322 MB |
34. Jsonb vs Json
• Input performance (parser)
Copy data (1,252,973 rows) as text, json,jsonb
copy tt from '/path/to/test.dump'
Text: 34 s - as is
Json: 37 s - json validation
Jsonb: 43 s - json validation, binary storage
35. Jsonb vs Json (binary storage)
• Access performance — get value by key
• Base: SELECT js FROM js;
• Jsonb: SELECT j->>'updated' FROM jb;
• Json: SELECT j->>'updated' FROM js;
Base: 0.6 s
Jsonb: 1 s 0.4
Json: 9.6 s 9
Jsonb ~ 20X faster Json
36. Jsonb vs Json
EXPLAIN ANALYZE SELECt count(*) FROM js WHERE js #>>'{tags,0,term}' = 'NYC';
QUERY PLAN
----------------------------------------------------------------------------
Aggregate (cost=187812.38..187812.39 rows=1 width=0)
(actual time=10054.602..10054.602 rows=1 loops=1)
-> Seq Scan on js (cost=0.00..187796.88 rows=6201 width=0)
(actual time=0.030..10054.426 rows=123 loops=1)
Filter: ((js #>> '{tags,0,term}'::text[]) = 'NYC'::text)
Rows Removed by Filter: 1252850
Planning time: 0.078 ms
Execution runtime: 10054.635 ms
(6 rows)
Json: no contains @> operator,
search first array element
37. Jsonb vs Json (binary storage)
EXPLAIN ANALYZE SELECT count(*) FROM jb WHERE jb @> '{"tags":[{"term":"NYC"}]}'::jsonb;
QUERY PLAN
---------------------------------------------------------------------------------------
Aggregate (cost=191521.30..191521.31 rows=1 width=0)
(actual time=1263.201..1263.201 rows=1 loops=1)
-> Seq Scan on jb (cost=0.00..191518.16 rows=1253 width=0)
(actual time=0.007..1263.065 rows=285 loops=1)
Filter: (jb @> '{"tags": [{"term": "NYC"}]}'::jsonb)
Rows Removed by Filter: 1252688
Planning time: 0.065 ms
Execution runtime: 1263.225 ms Execution runtime: 10054.635 ms
(6 rows)
Jsonb ~ 10X faster Json
38. Jsonb vs Json (GIN: key && value)
CREATE INDEX gin_jb_idx ON jb USING gin(jb);
EXPLAIN ANALYZE SELECT count(*) FROM jb WHERE jb @> '{"tags":[{"term":"NYC"}]}'::jsonb;
QUERY PLAN
---------------------------------------------------------------------------------------
Aggregate (cost=4772.72..4772.73 rows=1 width=0)
(actual time=8.486..8.486 rows=1 loops=1)
-> Bitmap Heap Scan on jb (cost=73.71..4769.59 rows=1253 width=0)
(actual time=8.049..8.462 rows=285 loops=1)
Recheck Cond: (jb @> '{"tags": [{"term": "NYC"}]}'::jsonb)
Heap Blocks: exact=285
-> Bitmap Index Scan on gin_jb_idx (cost=0.00..73.40 rows=1253 width=0)
(actual time=8.014..8.014 rows=285 loops=1)
Index Cond: (jb @> '{"tags": [{"term": "NYC"}]}'::jsonb)
Planning time: 0.115 ms
Execution runtime: 8.515 ms Execution runtime: 10054.635 ms
(8 rows)
Jsonb ~ 150X faster Json
39. Jsonb vs Json (GIN: hash path.value)
CREATE INDEX gin_jb_path_idx ON jb USING gin(jb jsonb_path_ops);
EXPLAIN ANALYZE SELECT count(*) FROM jb WHERE jb @> '{"tags":[{"term":"NYC"}]}'::jsonb;
QUERY PLAN
---------------------------------------------------------------------------------------
Aggregate (cost=4732.72..4732.73 rows=1 width=0)
(actual time=0.644..0.644 rows=1 loops=1)
-> Bitmap Heap Scan on jb (cost=33.71..4729.59 rows=1253 width=0)
(actual time=0.102..0.620 rows=285 loops=1)
Recheck Cond: (jb @> '{"tags": [{"term": "NYC"}]}'::jsonb)
Heap Blocks: exact=285
-> Bitmap Index Scan on gin_jb_path_idx
(cost=0.00..33.40 rows=1253 width=0) (actual time=0.062..0.062 rows=285 loops=1)
Index Cond: (jb @> '{"tags": [{"term": "NYC"}]}'::jsonb)
Planning time: 0.056 ms
Execution runtime: 0.668 ms Execution runtime: 10054.635 ms
(8 rows)
Jsonb ~ 1800X faster Json
41. Summary: PostgreSQL 9.4 vs Mongo 2.6.0
• Operator contains @>
• json : 10 s seqscan
• jsonb : 8.5 ms GIN jsonb_ops
• jsonb : 0.7 ms GIN jsonb_path_ops
• mongo : 1.0 ms btree index
• Index size
•Table size
•postgres : 1.3Gb
•mongo : 1.8Gb
•Input performance:
• Text : 34 s
• Json : 37 s
• Jsonb : 43 s
• mongo : 13 m
• jsonb_ops - 636 Mb (no compression, 815Mb)
jsonb_path_ops - 295 Mb
• jsonb_path_ops (tags) - 44 Mb USING gin((jb->'tags') jsonb_path_ops
• mongo (tags) - 387 Mb
mongo (tags.term) - 100 Mb
42. Jsonb (Apr, 2014)
• Documentation
• JSON Types, JSON Functions and Operators
• There are many functionality left in nested hstore
• Can be an extension
• Need query language for jsonb
• <,>,&& … operators for values
a.b.c.d && [1,2,10]
• Structural queries on paths
*.d && [1,2,10]
• Indexes !
43. Jsonb query
• Currently, one can search jsonb data using
• Contains operators - jsonb @> jsonb, jsonb <@ jsonb (GIN indexes)
jb @> '{"tags":[{"term":"NYC"}]}'::jsonb
Keys should be specified from root
● Equivalence operator — jsonb = jsonb (GIN indexes)
• Exists operators — jsonb ? text, jsonb ?! text[], jsonb ?& text[] (GIN indexes)
jb WHERE jb ?| '{tags,links}'
Only root keys supported
• Operators on jsonb parts (functional indexes)
SELECT ('{"a": {"b":5}}'::jsonb -> 'a'->>'b')::int > 2;
CREATE INDEX ….USING BTREE ( (jb->'a'->>'b')::int);
Very cumbersome, too many functional indexes
44. Jsonb query
• Need Jsonb query language
• More operators on keys, values
• Types support
• Schema support (constraints on keys, values)
• Indexes support
• Introduce Jsquery - textual data type and @@ match operator
jsonb @@ jsquery
45. Jsonb query language (Jsquery)
value_list
::= scalar_value
| value_list ',' scalar_value
array ::= '[' value_list ']'
scalar_value
::= null
| STRING
| true
| false
| NUMERIC
| OBJECT
…....
Expr ::= path value_expr
| path HINT value_expr
| NOT expr
| NOT HINT value_expr
| NOT value_expr
| path '(' expr ')'
| '(' expr ')'
| expr AND expr
| expr OR expr
path ::= key
| path '.' key_any
| NOT '.' key_any
key ::= '*'
| '#'
| '%'
| '$'
| STRING
….....
key_any ::= key
| NOT
value_expr
::= '=' scalar_value
| IN '(' value_list ')'
| '=' array
| '=' '*'
| '<' NUMERIC
| '<' '=' NUMERIC
| '>' NUMERIC
| '>' '=' NUMERIC
| '@' '>' array
| '<' '@' array
| '&' '&' array
| IS ARRAY
| IS NUMERIC
| IS OBJECT
| IS STRING
| IS BOOLEAN
46. Jsonb query language (Jsquery)
• # - any element array
• % - any key
• * - anything
• $ - current element
SELECT '{"a": {"b": [1,2,3]}}'::jsonb @@ 'a.b.# = 2';
SELECT '{"a": {"b": [1,2,3]}}'::jsonb @@ '%.b.# = 2';
SELECT '{"a": {"b": [1,2,3]}}'::jsonb @@ '*.# = 2';
select '{"a": {"b": [1,2,3]}}'::jsonb @@ 'a.b.# ($ = 2 OR $ < 3)';
• Use "double quotes" for key !
select 'a1."12222" < 111'::jsquery;
path ::= key
| path '.' key_any
| NOT '.' key_any
key ::= '*'
| '#'
| '%'
| '$'
| STRING
….....
key_any ::= key
| NOT
48. Jsonb query language (Jsquery)
• Type checking
select '{"x": true}' @@ 'x IS boolean'::jsquery,
'{"x": 0.1}' @@ 'x IS numeric'::jsquery;
?column? | ?column?
----------+----------
t | t
IS BOOLEAN
IS NUMERIC
IS ARRAY
IS OBJECT
select '{"a":{"a":1}}' @@ 'a IS object'::jsquery; IS STRING
?column?
----------
t
select '{"a":["xxx"]}' @@ 'a IS array'::jsquery, '["xxx"]' @@ '$ IS array'::jsquery;
?column? | ?column?
----------+----------
t | t
49. Jsonb query language (Jsquery)
• How many products are similar to "B000089778" and have
product_sales_rank in range between 10000-20000 ?
• SQL
SELECT count(*) FROM jr WHERE (jr-
>>'product_sales_rank')::int > 10000 and (jr->>
'product_sales_rank')::int < 20000 and
….boring stuff
• Jsquery
SELECT count(*) FROM jr WHERE jr @@ ' similar_product_ids &&
["B000089778"] AND product_sales_rank( $ > 10000 AND $ <
20000)'
• Mongodb
db.reviews.find( { $and :[ {similar_product_ids: { $in
["B000089778"]}}, {product_sales_rank:{$gt:10000,
50. Jsonb query language (Jsquery)
explain( analyze, buffers) select count(*) from jb where jb @> '{"tags":[{"term":"NYC"}]}'::jsonb;
QUERY PLAN
---------------------------------------------------------------------------------------------------------------
Aggregate (cost=191517.30..191517.31 rows=1 width=0) (actual time=1039.422..1039.423 rows=1 loops=1)
Buffers: shared hit=97841 read=78011
-> Seq Scan on jb (cost=0.00..191514.16 rows=1253 width=0) (actual time=0.006..1039.310 rows=285 loops=Filter: (jb @> '{"tags": [{"term": "NYC"}]}'::jsonb)
Rows Removed by Filter: 1252688
Buffers: shared hit=97841 read=78011
Planning time: 0.074 ms
Execution time: 1039.444 ms
explain( analyze,costs off) select count(*) from jb where jb @@ 'tags.#.term = "NYC"';
QUERY PLAN
--------------------------------------------------------------------
Aggregate (actual time=891.707..891.707 rows=1 loops=1)
-> Seq Scan on jb (actual time=0.010..891.553 rows=285 loops=1)
Filter: (jb @@ '"tags".#."term" = "NYC"'::jsquery)
Rows Removed by Filter: 1252688
Execution time: 891.745 ms
51. Jsquery (indexes)
• GIN opclasses with jsquery support
• jsonb_value_path_ops — use Bloom filtering for key matching
{"a":{"b":{"c":10}}} → 10.( bloom(a) or bloom(b) or bloom(c) )
• Good for key matching (wildcard support) , not good for range query
• jsonb_path_value_ops — hash path (like jsonb_path_ops)
{"a":{"b":{"c":10}}} → hash(a.b.c).10
• No wildcard support, no problem with ranges
List of relations
Schema | Name | Type | Owner | Table | Size | Description
--------+-------------------------+-------+----------+--------------+---------+-------------
public | jb | table | postgres | | 1374 MB |
public | jb_value_path_idx | index | postgres | jb | 306 MB |
public | jb_gin_idx | index | postgres | jb | 544 MB |
public | jb_path_value_idx | index | postgres | jb | 306 MB |
public | jb_path_idx | index | postgres | jb | 251 MB |
52. Jsquery (indexes)
explain( analyze,costs off) select count(*) from jb where jb @@ 'tags.#.term = "NYC"';
QUERY PLAN
-------------------------------------------------------------------------------------------------
Aggregate (actual time=0.609..0.609 rows=1 loops=1)
-> Bitmap Heap Scan on jb (actual time=0.115..0.580 rows=285 loops=1)
Recheck Cond: (jb @@ '"tags".#."term" = "NYC"'::jsquery)
Heap Blocks: exact=285
-> Bitmap Index Scan on jb_value_path_idx (actual time=0.073..0.073 rows=Index Cond: (jb @@ '"tags".#."term" = "NYC"'::jsquery)
Execution time: 0.634 ms
(7 rows)
53. Jsquery (indexes)
explain( analyze,costs off) select count(*) from jb where jb @@ '*.term = "NYC"';
QUERY PLAN
-------------------------------------------------------------------------------------------------
Aggregate (actual time=0.688..0.688 rows=1 loops=1)
-> Bitmap Heap Scan on jb (actual time=0.145..0.660 rows=285 loops=1)
Recheck Cond: (jb @@ '*."term" = "NYC"'::jsquery)
Heap Blocks: exact=285
-> Bitmap Index Scan on jb_value_path_idx (actual time=0.113..0.113 rows=Index Cond: (jb @@ '*."term" = "NYC"'::jsquery)
Execution time: 0.716 ms
(7 rows)
54. Citus dataset {
"customer_id": "AE22YDHSBFYIP",
"product_category": "Business & Investing",
"product_group": "Book",
"product_id": "1551803542",
"product_sales_rank": 11611,
"product_subcategory": "General",
"product_title": "Start and Run a Coffee Bar (Start "review_date": {
"$date": 31363200000
},
"review_helpful_votes": 0,
"review_rating": 5,
"review_votes": 10,
"similar_product_ids": [
"0471136174",
"0910627312",
"047112138X",
"0786883561",
"0201570483"
]
}
• 3023162 reviews from Citus
1998-2000 years
• 1573 MB
55. Jsquery (indexes)
explain (analyze, costs off) select count(*) from jr where
jr @@ ' similar_product_ids && ["B000089778"]';
QUERY PLAN
------------------------------------------------------------------------------------------------
Aggregate (actual time=0.359..0.359 rows=1 loops=1)
-> Bitmap Heap Scan on jr (actual time=0.084..0.337 rows=185 loops=1)
Recheck Cond: (jr @@ '"similar_product_ids" && ["B000089778"]'::jsquery)
Heap Blocks: exact=107
-> Bitmap Index Scan on jr_path_value_idx (actual time=0.057..0.057 rows=Index Cond: (jr @@ '"similar_product_ids" && ["B000089778"]'::jsquery)
Execution time: 0.394 ms
(7 rows)
56. Jsquery (indexes)
• No statistics, no planning :(
explain (analyze, costs off) select count(*) from jr where
jr @@ ' similar_product_ids && ["B000089778"]
AND product_sales_rank( $ > 10000 AND $ < 20000)';
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------Aggregate (actual time=126.149..126.149 rows=1 loops=1)
-> Bitmap Heap Scan on jr (actual time=126.057..126.143 rows=45 loops=1)
Recheck Cond: (jr @@ '("similar_product_ids" && ["B000089778"] &
"product_sales_rank"($ > 10000 & $ < 20000))'::jsquery)
Heap Blocks: exact=45
-> Bitmap Index Scan on jr_path_value_idx (actual time=126.029..126.029 rows=Index Cond: (jr @@ '("similar_product_ids" && ["B000089778"] &
"product_sales_rank"($ > 10000 & $ < 20000))'::jsquery)
Execution time: 129.309 ms !!! No statistics
(7 rows)
Not selective, better not use index!
58. Jsquery (indexes)
• If we rewrite query and use planner
explain (analyze,costs off) select count(*) from jr where
jr @@ ' similar_product_ids && ["B000089778"]'
and (jr->>'product_sales_rank')::int>10000 and (jr->>'product_sales_rank')::int<20000;
-------------------------------------------------------------------------------------------------------------------------------Aggregate (actual time=0.479..0.479 rows=1 loops=1)
-> Bitmap Heap Scan on jr (actual time=0.079..0.472 rows=45 loops=1)
Recheck Cond: (jr @@ '"similar_product_ids" && ["B000089778"]'::jsquery)
Filter: ((((jr ->> 'product_sales_rank'::text))::integer > 10000) AND
(((jr ->> 'product_sales_rank'::text))::integer < 20000))
Rows Removed by Filter: 140
Heap Blocks: exact=107
-> Bitmap Index Scan on jr_path_value_idx (actual time=0.041..0.041 rows=Index Cond: (jr @@ '"similar_product_ids" && ["B000089778"]'::jsquery)
Execution time: 0.506 ms Potentially, query could be faster Mongo !
(9 rows)
59. Jsquery (optimiser) — NEW !
• Jsquery now has built-in optimiser for simple queries.
explain (analyze, costs off) select count(*) from jr where
jr @@ 'similar_product_ids && ["B000089778"]
AND product_sales_rank( $ > 10000 AND $ < 20000)'
----------------------------------------------------------------------------
--------------------------------------------------------------
Aggregate (actual time=0.422..0.422 rows=1 loops=1)
-> Bitmap Heap Scan on jr (actual time=0.099..0.416 rows=45 loops=1)
Recheck Cond: (jr @@ '("similar_product_ids" && ["B000089778"] AND
"product_sales_rank"($ > 10000 AND $ < 20000))'::jsquery)
Rows Removed by Index Recheck: 140
Heap Blocks: exact=107
-> Bitmap Index Scan on jr_path_value_idx (actual
time=0.060..0.060 rows=185 loops=1)
Index Cond: (jr @@ '("similar_product_ids" && ["B000089778"]
AND "product_sales_rank"($ > 10000 AND $ < 20000))'::jsquery)
Execution time: 0.480 ms vs 7 ms MongoDB !
60. Jsquery (optimiser) — NEW !
• Jsquery now has built-in optimiser for simple queries.
Analyze query tree and push non-selective parts to recheck (like filter)
Selectivity classes:
1) Equality (x = c)
2) Range (c1 < x < c2)
3) Inequality (c > c1)
4) Is (x is type)
5) Any (x = *)
SELECT gin_debug_query_path_value('similar_product_ids && ["B000089778"]
AND product_sales_rank( $ > 10000 AND $ < 20000)');
gin_debug_query_path_value
-------------------------------------------------
similar_product_ids.# = "B000089778" , entry 0 +
61. Jsquery (optimiser) — NEW !
• Jsquery optimiser pushes non-selective operators to recheck
explain (analyze, costs off) select count(*) from jr where
jr @@ 'similar_product_ids && ["B000089778"]
AND product_sales_rank( $ > 10000 AND $ < 20000)'
----------------------------------------------------------------------------
--------------------------------------------------------------
Aggregate (actual time=0.422..0.422 rows=1 loops=1)
-> Bitmap Heap Scan on jr (actual time=0.099..0.416 rows=45 loops=1)
Recheck Cond: (jr @@ '("similar_product_ids" && ["B000089778"] AND
"product_sales_rank"($ > 10000 AND $ < 20000))'::jsquery)
Rows Removed by Index Recheck: 140
Heap Blocks: exact=107
-> Bitmap Index Scan on jr_path_value_idx (actual
time=0.060..0.060 rows=185 loops=1)
Index Cond: (jr @@ '("similar_product_ids" && ["B000089778"]
AND "product_sales_rank"($ > 10000 AND $ < 20000))'::jsquery)
Execution time: 0.480 ms
62. Jsquery (HINTING) — NEW !
• Jsquery now has HINTING ( if you don't like optimiser)!
explain (analyze, costs off) select count(*) from jr where jr @@ 'product_sales_rank > 10000'
--------------------------------------------------------------------------------------------------
--------
Aggregate (actual time=2507.410..2507.410 rows=1 loops=1)
-> Bitmap Heap Scan on jr (actual time=1118.814..2352.286 rows=2373140 loops=1)
Recheck Cond: (jr @@ '"product_sales_rank" > 10000'::jsquery)
Heap Blocks: exact=201209
-> Bitmap Index Scan on jr_path_value_idx (actual time=1052.483..1052.48
rows=2373140 loops=1)
Index Cond: (jr @@ '"product_sales_rank" > 10000'::jsquery)
Execution time: 2524.951 ms
• Better not to use index — HINT /* --noindex */
explain (analyze, costs off) select count(*) from jr where jr @@ 'product_sales_rank /*-- noindex
*/ > 10000';
----------------------------------------------------------------------------------
Aggregate (actual time=1376.262..1376.262 rows=1 loops=1)
-> Seq Scan on jr (actual time=0.013..1222.123 rows=2373140 loops=1)
Filter: (jr @@ '"product_sales_rank" /*-- noindex */ > 10000'::jsquery)
Rows Removed by Filter: 650022
Execution time: 1376.284 ms
63. Contrib/jsquery
• Jsquery index support is quite efficient ( 0.5 ms vs Mongo 7 ms ! )
• Future direction
• Make jsquery planner friendly
• Need statistics for jsonb
• Availability
• Jsquery + opclasses are available as extensions
• Grab it from https://github.com/akorotkov/jsquery (branch master) ,
we need your feedback !
• We will release it after PostgreSQL 9.4 release
• Need real sample data and queries !
64. PostgreSQL 9.4+
● Open-source
● Relational database
● Strong support of json
65. Better indexing ...
• GIN is a proven and effective index access method
• Need indexing for jsonb with operations on paths (no hash!) and values
• B-tree in entry tree is not good - length limit, no prefix compression
List of relations
Schema | Name | Type | Owner | Table | Size | Description
--------+-----------------------------+-------+----------+---------------+---------+-------------
public | jb | table | postgres | | 1374 MB |
public | jb_uniq_paths | table | postgres | | 912 MB |
public | jb_uniq_paths_btree_idx | index | postgres | jb_uniq_paths | 885 MB |text_pattern_ops
public | jb_uniq_paths_spgist_idx | index | postgres | jb_uniq_paths | 598 MB |now much less !
66. Better indexing ...
• Provide interface to change hardcoded B-tree in Entry tree
• Use spgist opclass for storing paths and values as is (strings hashed in values)
• We may go further - provide interface to change hardcoded B-tree in
posting tree
• GIS aware full text search !
• New index access method
CREATE INDEX … USING VODKA
67. GIN History
• Introduced at PostgreSQL Anniversary Meeting in Toronto, Jul 7-8, 2006
by Oleg Bartunov and Teodor Sigaev
68. GIN History
• Introduced at PostgreSQL Anniversary Meeting in Toronto, Jul 7-8, 2006
by Oleg Bartunov and Teodor Sigaev
• Supported by JFG Networks (France)
• «Gin stands for Generalized Inverted iNdex and should be considered as
a genie, not a drink.»
• Alexander Korotkov, Heikki Linnakangas have joined GIN++
development in 2013
69. GIN History
• From GIN Readme, posted in -hackers, 2006-04-26
TODO
----
Nearest future:
* Opclasses for all types (no programming, just many catalog changes).
Distant future:
* Replace B-tree of entries to something like GiST (VODKA ! 2014)
* Add multicolumn support
* Optimize insert operations (background index insertion)
70. GIN index structure for jsonb
{
"product_group": "Book",
"product_sales_rank": 15000
},
{
"product_group": "Music",
"product_sales_rank": 25000
}
71. Vodka index structure for jsonb
{
"product_group": "Book",
"product_sales_rank": 15000
},
{
"product_group": "Music",
"product_sales_rank": 25000
}
72. CREATE INDEX … USING VODKA
• Delicious bookmarks, mostly text data
set maintenance_work_mem = '1GB';
List of relations
Schema | Name | Type | Owner | Table | Size | Description
--------+--------------------+-------+----------+-------+---------+-------------
public | jb | table | postgres | | 1374 MB | 1252973 rows
public | jb_value_path_idx | index | postgres | jb | 306 MB | 98769.096
public | jb_gin_idx | index | postgres | jb | 544 MB | 129860.859
public | jb_path_value_idx | index | postgres | jb | 306 MB | 100560.313
public | jb_path_idx | index | postgres | jb | 251 MB | 68880.320
public | jb_vodka_idx | index | postgres | jb | 409 MB | 185362.865
public | jb_vodka_idx5 | index | postgres | jb | 325 MB | 174627.234 new spgist
(6 rows)
73. CREATE INDEX … USING VODKA
select count(*) from jb where jb @@ 'tags.#.term = "NYC"';
-------------------------------------------------------------------------------------------
Aggregate (actual time=0.423..0.423 rows=1 loops=1)
-> Bitmap Heap Scan on jb (actual time=0.146..0.404 rows=285 loops=1)
Recheck Cond: (jb @@ '"tags".#."term" = "NYC"'::jsquery)
Heap Blocks: exact=285
-> Bitmap Index Scan on jb_vodka_idx (actual time=0.108..0.108 rows=285 loops=Index Cond: (jb @@ '"tags".#."term" = "NYC"'::jsquery)
Execution time: 0.456 ms (0.634 ms, GIN jsonb_value_path_ops)
select count(*) from jb where jb @@ '*.term = "NYC"';
-------------------------------------------------------------------------------------------
Aggregate (actual time=0.495..0.495 rows=1 loops=1)
-> Bitmap Heap Scan on jb (actual time=0.245..0.474 rows=285 loops=1)
Recheck Cond: (jb @@ '*."term" = "NYC"'::jsquery)
Heap Blocks: exact=285
-> Bitmap Index Scan on jb_vodka_idx (actual time=0.214..0.214 rows=285 loops=Index Cond: (jb @@ '*."term" = "NYC"'::jsquery)
Execution time: 0.526 ms (0.716 ms, GIN jsonb_path_value_ops)
74. CREATE INDEX … USING VODKA
• CITUS data, text and numeric
set maintenance_work_mem = '1GB';
List of relations
Schema | Name | Type | Owner | Table | Size | Description
--------+--------------------+-------+----------+-------+---------+-------------
public | jr | table | postgres | | 1573 MB | 3023162 rows
public | jr_value_path_idx | index | postgres | jr | 196 MB | 79180.120
public | jr_gin_idx | index | postgres | jr | 235 MB | 111814.929
public | jr_path_value_idx | index | postgres | jr | 196 MB | 73369.713
public | jr_path_idx | index | postgres | jr | 180 MB | 48981.307
public | jr_vodka_idx3 | index | postgres | jr | 240 MB | 155714.777
public | jr_vodka_idx4 | index | postgres | jr | 211 MB | 169440.130 new spgist
(6 rows)
75. CREATE INDEX … USING VODKA
explain (analyze, costs off) select count(*) from jr where jr @@ ' similar_product_ids && ["QUERY PLAN
-------------------------------------------------------------------------------------------
Aggregate (actual time=0.200..0.200 rows=1 loops=1)
-> Bitmap Heap Scan on jr (actual time=0.090..0.183 rows=185 loops=1)
Recheck Cond: (jr @@ '"similar_product_ids" && ["B000089778"]'::jsquery)
Heap Blocks: exact=107
-> Bitmap Index Scan on jr_vodka_idx (actual time=0.077..0.077 rows=185 loops=1)
Index Cond: (jr @@ '"similar_product_ids" && ["B000089778"]'::jsquery)
Execution time: 0.237 ms (0.394 ms, GIN jsonb_path_value_idx)
(7 rows)
83. Summary
• contrib/jsquery for 9.4
• Jsquery - Jsonb Query Language
• Two GIN opclasses with jsquery support
• Grab it from https://github.com/akorotkov/jsquery (branch master)
• Prototype of VODKA access method
• Plans for improving indexing infrastructure
• This work was supported by
84. Another view on VODKA
• VODKA CONNECTING INDEXES
• composite index, which combines different access methods
• Nested search trees