I have a PostgreSQL table which is defined as follows.
"""
CREATE TYPE similarity AS (
user_id integer,
similarity real,
rank integer
)
""",
"""
CREATE TABLE user_similarities (
user_id int REFERENCES books_user_id (user_id) ON UPDATE CASCADE ON DELETE CASCADE,
similarities similarity[]
)
"""
Here is an example that I use for testing:
What I want to achieve is to update one element of my composite type (similarity) in the array. An example would be to change the similarity to a given value lets say 1, of user_id = 3 and similarities.user_id = 10.
with the following query, I can select user_id = 3 and similarities.similarity = 10, but I don't know how to update my table.
sql = """with list_1 as (SELECT *, unnest(similarities) as list_similarities FROM user_similarities WHERE user_id = 3), id_1
as (SELECT * FROM list_1 WHERE(list_1.list_similarities).user_id=10 ) SELECT * FROM id_1"""
I tried the following:
with list_1 as (SELECT *, unnest(similarities) as list_similarities FROM user_similarities WHERE user_id = 3),
id_1 as (SELECT * FROM list_1 WHERE(list_1.list_similarities).user_id=10 ) UPDATE id_1 SET
list_similarities.similarity = 1
But I get the error message: relation "id_1" does not exist LINE 2: ...ERE(list_1.list_similarities).user_id=10 ) UPDATE id_1 SET l...
Here is the whole function:
def update_similarity(connection,id_ ):
sql = """with list_1 as (SELECT *, unnest(similarities) as list_similarities FROM user_similarities WHERE user_id = 3), id_1
as (SELECT * FROM list_1 WHERE(list_1.list_similarities).user_id=10 ) UPDATE id_1 SET list_similarities.similarity = 1 """
to_insert = (id_,)
bol = 0
try:
conn = connection
# create a new cursor
cur = conn.cursor()
# execute the INSERT statement
cur.execute(sql, to_insert)
request = cur.fetchall()
if len(request) > 0:
bol = 1
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
return bol
Any help would be appreciated.

similarityfield in that table's array, whereuser_id = 3(or so)? So my question is, do you want to update ALL the objects in that record'ssimilaritiesarray, or only certain ones? If not all, then what's the criteria for determining which elements in the array to update?