Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write JSON column type to Postgres with PySpark?

I have a Postgresql table that has a column with data type JSONB.

How do I insert DataFrame to the Postgresql table via JDBC?

If I have a UDF to convert the the body column to the JSONB Postgresql data type, what is the corresponding pyspark.sql.types should I use?

Postgresql Table with a JSONB column:

CREATE TABLE dummy (
  id bigint,
  body JSONB
);

Thanks!

like image 580
RichardKang Avatar asked Sep 07 '17 04:09

RichardKang


People also ask

Does Postgres support JSON data type?

PostgreSQL offers two types for storing JSON data: json and jsonb . To implement efficient query mechanisms for these data types, PostgreSQL also provides the jsonpath data type described in Section 8.14. 7. The json and jsonb data types accept almost identical sets of values as input.

Can you store any string in a JSON Postgres data type?

You can save any valid json value to either json or to a jsonb column. But you cannot bind it as string/ text / varchar , if you use prepared statements (use casts instead in sql, like UPDATE ... SET json_col = $1::json or bind it as unknown ).

What is Jsonb type?

The JSONB data type stores JSON (JavaScript Object Notation) data as a binary representation of the JSONB value, which eliminates whitespace, duplicate keys, and key ordering. JSONB supports GIN indexes.

What is the difference between JSON and Jsonb in Postgres?

PostgreSQL jsonb JSON data type stores the exact copy of input text in JSON. Jsonb stores the data as binary code. Basically, it stores the data in binary form which is not an ASCII/ UTF-8 string. Json preserves the original formatting like the whitespaces as well as the ordering of keys.


1 Answers

It turned out if I set "stringtype":"unspecified" as the properties of the JDBC, Postgres will cast automatically:


    properties = {
        "user": "***",
        "password": "***",
        "stringtype":"unspecified"
    }
    df.write.jdbc(url=url, table="dummy", properties=properties)

like image 196
RichardKang Avatar answered Oct 05 '22 06:10

RichardKang