как эмулировать, “вставляют, игнорируют” и “на дублирующемся ключевом обновлении” (sql слияние) с postgresql?

Вы можете использовать df.na.fill для замены нулей нулями, например:

>>> df = spark.createDataFrame([(1,), (2,), (3,), (None,)], ['col'])
>>> df.show()
+----+
| col|
+----+
|   1|
|   2|
|   3|
|null|
+----+

>>> df.na.fill(0).show()
+---+
|col|
+---+
|  1|
|  2|
|  3|
|  0|
+---+
128
задан Ondra Žižka 4 June 2018 в 09:57
поделиться

2 ответа

Try to do an UPDATE. If it doesn't modify any row that means it didn't exist, so do an insert. Obviously, you do this inside a transaction.

You can of course wrap this in a function if you don't want to put the extra code on the client side. You also need a loop for the very rare race condition in that thinking.

There's an example of this in the documentation: http://www.postgresql.org/docs/9.3/static/plpgsql-control-structures.html, example 40-2 right at the bottom.

That's usually the easiest way. You can do some magic with rules, but it's likely going to be a lot messier. I'd recommend the wrap-in-function approach over that any day.

This works for single row, or few row, values. If you're dealing with large amounts of rows for example from a subquery, you're best of splitting it into two queries, one for INSERT and one for UPDATE (as an appropriate join/subselect of course - no need to write your main filter twice)

31
ответ дан 24 November 2019 в 00:35
поделиться

Похоже, PostgreSQL поддерживает объект схемы, называемый правилом .

http://www.postgresql.org/docs/current/static/rules-update. html

Вы можете создать правило ON INSERT для данной таблицы, заставляя его делать НИЧЕГО , если строка существует с данным значением первичного ключа, или заставляя его выполнять UPDATE вместо INSERT , если существует строка с заданным значением первичного ключа.

Я сам не пробовал это делать, поэтому я не могу говорить по опыту или предлагать пример .

12
ответ дан 24 November 2019 в 00:35
поделиться
Другие вопросы по тегам:

Похожие вопросы: