As per this JSON Insert into a MySQL table or update if exists, I got answer mysql to insert/update the below json.
"google",
"20180510",
"{
"gmail_page_viewed" : 12000300,
"search_page_viewed" : 9898884726423
}"
into the SCHEMA
CREATE TABLE TAG_COUNTER (
account varchar(36) NOT NULL,
time_id INT NOT NULL,
counters JSON,
PRIMARY KEY (account, time_id)
)
like below
INSERT INTO `TAG_COUNTER`
(`account`, `time_id`, `counters`)
VALUES
('google', '20180510', '{"gmail_page_viewed": 1, "search_page_viewed": 1}'),
('google', '20180510', '{"gmail_page_viewed": 1, "search_page_viewed": 1}'),
('google', '20180511', '{"gmail_page_viewed": 1, "search_page_viewed": 1}'),
('google', '20180511', '{"gmail_page_viewed": 1, "search_page_viewed": 1}'),
('google', '20180512', '{"gmail_page_viewed": 1, "search_page_viewed": 1}')
ON DUPLICATE KEY UPDATE `counters` =
JSON_SET(`counters`,
'$."gmail_page_viewed"',
IFNULL(`counters` ->> '$."gmail_page_viewed"', 0) + 1,
'$."search_page_viewed"',
IFNULL(`counters` ->> '$."search_page_viewed"', 0) + 1
);
However it is difficult to retrieve the data from it using group by, since json key is dynamic and not static.
So if i change my json to have static keys (e.g. page_name, page_visits) to the below format, to make retrieval (groupby/orderby) is easy.
"google",
"20180510",
'{
"gmail_page_viewed" : {"page_name" : "gmail_page_viewed", "page_visits" : 12000300},
"search_page_viewed" : {"page_name" : "search_page_viewed", "page_visits" : 12000300}
}"
But i couldn't figure out how to prepare INSERT ON DUPLICATE KEY UPDATE
query. I have tried for more than 6 hours, but no luck, either data is not inserted properly, or not updating the visit count properly. sometime quote gets added into the content.
Could anyone help me on this?