I'm querying my database using Gorm and then using gin's c.JSON to marshal the structs to json.
It's a large query with not so much result ( < 100k ) and i'm having an issue with the time it takes ( 6-10 seconds ) to marshal the data.
I have no idea where to start to resolve the issue.
[2019-07-02 14:41:04] [946.63ms] SELECT big slow query
[62861 rows affected or returned ]
[GIN] 2019/07/02 - 14:41:11 | 200 | 7.92347114s | ip | GET /api/date/2019-05-30
[2019-07-02 14:40:44] [660.47ms] SELECT big slow query
[7583 rows affected or returned ]
[GIN] 2019/07/02 - 14:40:54 | 200 | 10.841096216s | ip | GET /api/dailies
[2019-07-02 14:43:49] [154.13ms] SELECT simple query
[11 rows affected or returned ]
[GIN] 2019/07/02 - 14:43:49 | 200 | 158.256792ms | ip | GET /api/dailycount
As you can see query 1 and 2 resolve in 600-900 ms , it's slow but it can be optimised separately.
The issue is that the response of the server take 7.9 and 10.8s ..!
For the smaller query there isn't much difference but i'm not getting why this is happening.
The go code for one of the route is pretty straightforward and similare for all routes :
var alertList []AlertJson
dbInstance.Debug().Raw("SELECT big query").Scan(&alertList)
c.JSON(http.StatusOK, gin.H{"alerts": alertList})
10.2 second for the second query with 7583rows to marshal seem pretty insane to me.
There was immense lag on my server provider and just in fact the 10 second is indeed the delay for me to receive the data as mentioned by peter.
Related
Lets say I have a table like so:
webpages
id | url
------------------------
1 | http://example.com/path
2 | example2.biz/another/path
3 | https://www.example3.net/another/path
And I want to search which webpages' url column is a substring of an input string. I know I can do it like this:
SELECT id FROM webpages WHERE STRPOS(url, 'example.com/path/to/some/content') > 0;
Expected result: 1
But I'm not sure how I might optimize this kind of query to run faster. Is there a way?
I found this article, it seems to suggest not - though I'm not sure if that's still true as it's from over a decade ago.
https://www.postgresql.org/message-id/046801c96b06%242cb14280%248613c780%24%40r%40sbcglobal.net
Let's say I have a Core Data database for NSPredicate rules.
enum PredicateType,Int {
case beginswith
case endswith
case contains
}
My Database looks like below
+------+-----------+
| Type | Content |
+------+-----------+
| 0 | Hello |
| 1 | end |
| 2 | somevalue |
| 0 | end |
+------+-----------+
I have a content "This is end". How can I query Core Data to check if there is any rule that satisfies this content? It should find second entry on the table
+------+-----------+
| Type | Content |
+------+-----------+
| 1 | end |
+------+-----------+
but shouldn't find
+------+-----------+
| Type | Content |
+------+-----------+
| 0 | end |
+------+-----------+
Because in this sentence end is not at the beginning.
Currently I am getting all values, Create predicate with Content and Type and query the database again which is a big overhead I believe.
They way you doing it now is correct. You first need to build your predicate (which in your case is very complex operation that also requires fetching) and run each predicate to see if which one matches.
I wouldn't be so quick to assume that there is a huge overhead with this. If your data set is small (<300) I would suspect that there would be no problem with this at all. If you are experencing problems then (and only then!) you should start optimizing.
If you see the app is running too slowly then use instrements to see where the issue is. There are two possible places that I could see having perforance issues - 1) the fetching of all the predicates from the database and 2) the running of all of the predicates.
If you want to make the fetching faster, then I would recommend using a NSFetchedResultsController. While it is generally used to keep data in sync with a tableview it can be used for any data that you want to have a correct data for at any time. With the controller you do a single fetch and then it monitors core-data and keeps itself up to data. Then when you you need all of the predicate instead of doing a fetch, you simply access the contoller's fetchedObjects property.
If you find that running all the predicates are taking a long time, then you can improve the running for beginsWith and endsWith by a clever use of a bianary search. You keep two arrays of custom predicate objects, one sorted alphabetically and the other will all the revered strings sorted alphabetically. To find which string it begins with use indexOfObject:inSortedRange:options:usingComparator: to find the relevant objects. If don't know how you can improve contains. You could see if running string methods on the objects is faster then NSPredicate methods. You could also try running the predicates on a background thread concurrently.
Again, you shouldn't do any of this unless you find that you need to. If your dataset is small, then the way you are doing it now is fine.
I'm having issues concurrently writing to a Redshift db. Writing to the db using a single connection works well, but is a little slow, so I am trying to use multiple concurrent connections but it looks like there can only be a single transaction at a time.
I investigated by running the following python script alone, and then running it 4 times simultaneously.
import psycopg2
import time
import os
if __name__ == "__main__":
rds_conn = psycopg2.connect(host="www.host.com", port="5439", dbname='db_name', user='db_user', password='db_pwd')
cur = rds_conn.cursor()
with open("tmp/test.query", 'r') as file:
query = file.read().replace('\n', '')
counter = 0
start_time = time.time()
try:
while True:
cur.execute(query)
rds_conn.commit() # first commit location
print("sent couter: %s" % counter)
counter += 1
except KeyboardInterrupt:
# rds_conn.commit() # secondary commit location
total_time = time.time() - start_time
queries_per_sec = counter / total_time
print("total queries/sec: %s" % queries_per_sec)
The test.query file being loaded up is a multi-row insert file ~16.8mb that looks a little like:
insert into category_stage values
(default, default, default, default),
(20, default, 'Country', default),
(21, 'Concerts', 'Rock', default);
(Just a lot longer)
The results of the scripts showed:
---------------------------------------------------
| process count | queries/sec | total queries/sec |
---------------------------------------------------
| 1 | 0.1786 | 0.1786 |
---------------------------------------------------
| 8 | 0.0359 | 0.2872 |
---------------------------------------------------
...which is far from the increase I'm looking for. When you can see the counter increasing across the scripts there's a clear circular pattern where each waits for the prior script's query to finish.
When the commit is moved from the first commit location to the second commit location (so commits only when the script is interrupted), only one script advances at a time. If that isn't a clear indication of some sort of transaction lock, I don't know what is.
As far as I can tell from searching, there's no document that says we can't have concurrent transactions, so what could the problem be? It's crossed my mind that the query size is so large that only one can be performed at a time, but I would have expected Redshift to have much more than ~17mb per transaction.
Inline with Guy's comment, I ended up using a COPY from an S3 bucket. This ended up being an order of magnitude faster, requiring only a single thread to call the query, and then allowing AWS to process the files from S3 in parallel. I used the guide detailed here and managed to insert about 120Gb of data in just over an hour.
Currently I have a table schema that looks like this:
| id | visitor_ids | name |
|----|-------------|----------------|
| 1 | {abc,def} | Chris Houghton |
| 2 | {ghi} | Matt Quinn |
The visitor_ids are all GUIDs, I've just shortened them for simplicity.
A user can have multiple visitor ids, hence the array type.
I have a GIN index created on the visitor_ids field.
I want to be able to lookup users by a visitor id. Currently we're doing this:
SELECT *
FROM users
WHERE visitor_ids && array['abc'];
The above works, but it's really really slow at scale - it takes around 45ms which is ~700x slower than a lookup by the primary key. (Even with the GIN index)
Surely there's got to be a more efficient way of doing this? I've looked around and wasn't able to find anything.
Possible solutions I can think of could be:
The current query is just bad and needs improving
Using a separate user_visitor_ids table
Something smart with special indexes
Help appreciated :)
I tried the second solution - 700x faster. Bingo.
I feel like this is an unsolved problem however, what's the point in adding arrays to Postgres when the performance is so bad, even with indexes?
We have used Kaminari for paginating records. We have hacked total_count method because giving a total count is very slow after 2m + records.
def total_count
#_hacked_total_count || (#_hacked_total_count = self.connection.execute("SELECT (reltuples)::integer FROM pg_class r WHERE relkind = 'r' AND relname ='#{table_name}'").first["reltuples"].to_i)
end
This returns approximate count of total records in the table which is fine.
However, that number is totally irrelevant when there is a search query.
I am looking for a fast way to return some number for search queries as well. (Doesn't need to be totally exact -- but needs to be meaningful (i.e. somewhat pertaining to the search query)
Please suggest if our approach to get total count of records as mentioned above is not correct.
P.S - We are using Postgres as our database provider and Rails as web development framework.
After stumbling upon this for couple of days, I did this by using EXPLAIN query and then extracting count rows count.
Here is the code snippet I wrote:
query_plan = ActiveRecord::Base.connection.execute("EXPLAIN <query>").first["QUERY PLAN"]
query_plan.match(/rows=(\d+)/)[1].to_i # returns the rows count
With this I can safety remove reltuples query.