переведи Storing data with a dynamic structure in relational databases is not a trivial…
- User
переведи Storing data with a dynamic structure in relational databases is not a trivial pro- blem – these databases are well-suited for structured data with lots of relationships. While the most-popular way of persisting data with open schema is using a docu- ment database, sometimes it is not possible due to the need for ACID transactions or highly relational types of queries. There are also data models that allow for sto- ring this kind of data in relational databases, such as Entity-Attribute-Value [21] or Inverted Index [27]; however, their main weaknesses is their complexity in preparing queries, execution time, and model readability. Our goal was to develop a new data model to store data with a dynamic structure in the relational database with query performance comparable to that of document databases and a structure simpler and more readable than in Entity-Attribute-Value. Improving the open schema data model has an impact on several fields of science, such as medicine (clinical databases) or forensic science (criminal data), where the numbers of the types and attributes of objects are enormous and feature a lot of relationships between them. Inspiration for our research was closing the gap between relational databases and NoSQL databases through introducing JSON as a native type [16]. This facilitated a new approach to storing data with a dynamic schema. The built-in support for the JSON type depends on the database engine. The first relational database management system that introduced native support for JSON was PostgreSQL [24], followed by MySQL [20] and Oracle Database [11]. Other databases like Microsoft SQL Server [23] provide only a library to handle JSON stored in the text column. The inspiration for our work was from two issues. The first was the problem of optimal data storage and analysis of dynamic multi-domain criminal data [5]. Storing and processing dynamic data is prevalent in many other domains as well, such as clinical databases [3] or biomedical databases [21]. These databases have been using well-known and mature Entity-Attribute-Value representation to organize data. Our second inspiration was finding and testing a better data model. We decided to use a JSON document to store open schema data, inspired by the Sinew system. This paper presents our open schema data model in a relational database. The model was tested by using carefully selected use cases in the field of criminal data. It was also compared with the Entity-Attribute-Value data model and MongoDB as the most-popular representative of document database engines. The results of our research show that using JSON to create a new dynamic data model simplifies and improves the current well-known data models, and it can replace current solutions
- Assistant
- User
переведи JavaScript Object Notification (JSON) [2] is a common data-interchange format de- signed primarily to serialize and transmit data over a network. It is used, for example, in the exchange of data between a client and server, REST-based services, and storing data in a NoSQL [9] database – MongoDB [4]. JSON has many advantages: it is rela- tively lightweight (when compared to alternatives such as XML), easy for humans to read and write as a text format, and has good support in many popular programming languages. A JSON object consists of key-value pairs, where the key is a string and the value can be any JSON data type: string, number, another JSON object, or array – see example in Figure 1. One of the extensions of this format is JSONB introduced by PostgreSQL. It allows for storing JSON as a binary object as opposed to a raw string. The purpose of such an approach is to facilitate the use of indexes and handle objects without the
- Assistant
JavaScript Object Notification (JSON) — это общий формат обмена данными, разработанный в первую очередь для сериализации и передачи данных по сети. Он используется, например, для обмена данными между клиентом и сервером, в REST-сервисах и для хранения данных в NoSQL базе данных — MongoDB. JSON имеет много преимуществ: он сравнительно легковесен (по сравнению с такими альтернативами, как XML), легко читаем и пишется людьми в текстовом формате, а также имеет хорошую поддержку во многих популярных языках программирования.
JSON-объект состоит из пар "ключ-значение", где ключ — это строка, а значение может быть любого типа данных JSON: строка, число, другой JSON-объект или массив — см. пример на рисунке 1.
Одним из расширений этого формата является JSONB, введённый PostgreSQL. Он позволяет хранить JSON в виде двоичного объекта, а не в виде сырой строки. Цель такого подхода — упростить использование индексов и управление объектами без необходимости преобразования в строку.
- User
переведи need for parsing strings. A summary of the advantages of introducing binary JSON format in PostgreSQL (including a performance comparison) can be found in [14].
- Assistant
необходимости парсинга строк. Обзор преимуществ введения двоичного формата JSON в PostgreSQL (включая сравнительный анализ производительности) можно найти в [14].
- User
передвеи NoSQL database systems have recently been gaining in popularity. These databases provide schema flexi- bility compared to traditional relational databases like PostgreSQL, but consequently give up certain desir- able features such as ACID guarantees. One compro- mise is to store schemaless documents within a re- lational database—an architecture which PostgreSQL has recently made possible by adding native support for JSON (JavaScript Object Notation), a common format for multi-level key-value documents. Currently, PostgreSQL provides validation of JSON documents upon input and native operators for query- ing operators within a JSON document. However, it stores JSON documents internally as text, which is in- efficient for many use cases. In this paper, we imple- ment support for BSON (Binary JSON), a lightweight binary encoding format for JSON-like documents which enables fast traversals. We observe that using BSON to store documents increases performance by two to eight times when querying keys within documents, without compromising document insertion times.
- Assistant
Системы баз данных NoSQL в последнее время становятся всё более популярными. Эти базы данных обеспечивают гибкость схемы по сравнению с традиционными реляционными базами данных, такими как PostgreSQL, но, следовательно, отказываются от некоторых желаемых функций, таких как гарантии ACID. Одним из компромиссов является хранение документов без схем в реляционной базе данных — архитектуры, которую PostgreSQL недавно реализовал, добавив нативную поддержку JSON (JavaScript Object Notation), общему формату для многоуровневых документов в формате "ключ-значение".
В настоящее время PostgreSQL предоставляет валидацию JSON-документов при вводе и нативные операторы для выполнения запросов внутри JSON-документа. Однако он хранит JSON-документы внутренно в виде текста, что неэффективно для многих сценариев использования. В этой статье мы реализуем поддержку BSON (Binary JSON) — легковесного двоичного формата кодирования для документов, подобных JSON, который позволяет выполнять быстрые обходы. Мы наблюдаем, что использование BSON для хранения документов увеличивает производительность в два-восемь раз при запросах к ключам внутри документов, не ухудшая время вставки документов.
- User
переведи This paper has presented an implementation of BSON for PostgreSQL which provides significant perfor- mance benefits over text-based JSON when querying within a schemaless document. As RDBMSs try to compete with NoSQL databases by offering support for storage of documents, read performance will be a crucial differentiator, and implementing performant data storage formats such as BSON could prove to be a major equalizer. In future work, we plan to extend our code to cover all data types, and add further operators for efficient querying. Additionally, our BSON implementation is currently baked into a fork of the PostgreSQL source code, but it would be far more useful to the commu- nity if it were implemented as an external module. We plan to do further development work to make the code production-ready, add unit tests, and release it as an open source extension
- Assistant
В этой статье представлена реализация BSON для PostgreSQL, которая обеспечивает значительные преимущества в производительности по сравнению с текстовым JSON при выполнении запросов внутри документа без схемы. Поскольку реляционные СУБД пытаются конкурировать с NoSQL базами данных, предлагая поддержку хранения документов, производительность чтения станет ключевым фактором различия, и внедрение эффективных форматов хранения данных, таких как BSON, может оказаться важным уравнителем возможностей.
В будущем мы планируем расширить наш код, чтобы охватить все типы данных, а также добавить дополнительные операторы для эффективных запросов. Кроме того, наша реализация BSON в настоящее время интегрирована в форк исходного кода PostgreSQL, но она была бы гораздо более полезной для сообщества, если бы была реализована в качестве внешнего модуля. Мы планируем провести дальнейшую разработку, чтобы сделать код готовым к использованию в производственной среде, добавить юнит-тесты и выпустить его в качестве расширения с открытым исходным кодом.
- User
перведи BSON [7] is a binary serialization of JSON-like docu- ments, developed for the NoSQL database MongoDB and designed for performant traversal. It is generally capable of storing any JSON document, with some minor caveats. The biggest difference is that JSON stores numbers as arbitrary precision character strings, whereas BSON can only store numbers as 32- and 64- bit integers or 64-bit double precision floats, in order to make storage simpler. (Of course, a careful program- mer can easily store arbitrary precision numbers as
- Assistant
BSON (Binary JSON) — это бинарная сериализация документов, подобных JSON, разработанная для NoSQL базы данных MongoDB и предназначенная для высокопроизводительного обхода. Он в целом способен хранить любой JSON-документ, с некоторыми незначительными оговорками. Основное отличие заключается в том, что JSON хранит числа в виде строк символов произвольной точности, в то время как BSON может хранить числа только как 32- и 64-битные целые числа или 64-битные числа с плавающей точкой двойной точности, чтобы упростить хранение. (Конечно, внимательный программист может легко хранить числа произвольной точности как...)
- User
переведи strings in BSON, just as in JSON.) Additionally, BSON enforces a maximum document size of 16MB (which is unlikely to be exceeded in most circumstances). BSON has several advantages compared to JSON which enable fast traversal. Many types (e.g. integers, booleans) are stored as fixed length fields, as opposed to variable length fields which must be parsed in JSON. For example, a boolean in BSON is represented by a single byte, as opposed to several bytes representing the word ”true” or ”false” in JSON. Additionally, BSON uses native C data types for many types such as integers and floats, which enables compact storage and more efficient parsing. Finally, BSON also encodes length information for variable length fields like strings, so they can be skipped over easily when querying for a specific key deep in the document. BSON is not necessarily more compact on disk than the equivalent JSON, but can almost always be traversed more quickly for these reasons
- Assistant
строки в BSON, так же как и в JSON.) Кроме того, BSON требует максимальный размер документа в 16 МБ (что в большинстве случаев маловероятно будет превышено).
У BSON есть несколько преимуществ по сравнению с JSON, которые обеспечивают быстрый обход. Многие типы (например, целые числа, булевы значения) хранятся как поля фиксированной длины, в отличие от полей переменной длины, которые необходимо парсить в JSON. Например, булевое значение в BSON представляется одним байтом, в то время как в JSON для представления слов "true" или "false" требуется несколько байтов. Кроме того, BSON использует нативные типы данных C для многих типов, таких как целые числа и числа с плавающей запятой, что обеспечивает компактное хранение и более эффективный парсинг. Наконец, BSON также кодирует информацию о длине для полей переменной длины, таких как строки, чтобы их можно было легко пропустить при запросе конкретного ключа в глубине документа. BSON не обязательно более компактен на диске, чем эквивалентный JSON, но по этим причинам его обход практически всегда происходит быстрее.
- User
переведи In the EAV model (Figure 3), it is hard to store dynamic objects with relations- hips. The id and type of the object are stored in the entity table, and they are used to find all related attributes and associated values from the table value. The relati- onships are stored in a separate table entity_relation, which contains information about the involved objects (left, right) and type of relationship (relation_type). However, if we want to store the attributes of the relationship itself, we have to represent relationships as entities and introduce another level of indirection by ha- ving entity_relation store only the IDs of these entities. From this open schema, we used dictionary definitions of the object and relationship types. Additionally, we moved ID to a table with the JSON document. We decided that an associative table with the relationships between entities used in EAV/CR almost fulfills its assumption, so we adapted it to the JSON model, adding a structure to store dynamic attributes
- Assistant
В модели EAV (Рисунок 3) трудно хранить динамические объекты со связями. Идентификатор и тип объекта хранятся в таблице сущностей и используются для поиска всех связанных атрибутов и соответствующих значений из таблицы значений. Связи хранятся в отдельной таблице entity_relation, которая содержит информацию о вовлеченных объектах (левом и правом) и типе связи (relation_type). Однако, если мы хотим хранить атрибуты самой связи, нам необходимо представить связи как сущности и ввести еще один уровень косвенности, сохраняя в таблице entity_relation только идентификаторы этих сущностей. Из этой открытой схемы мы использовали словарные определения типов объектов и отношений. Кроме того, мы переместили идентификатор в таблицу с документом JSON. Мы решили, что ассоциативная таблица со связями между сущностями, используемыми в EAV/CR, почти выполняет свои предположения, поэтому мы адаптировали ее к модели JSON, добавив структуру для хранения динамических атрибутов.