Poor performance on high volume data sets - orientdb

I am having poor performance on queries on classes that have a high record count. I am running some pretty straight forward queries but the performance is unusable. I really like orientdb and this is my 5th development project with odb as a backend. However, this particular project is forcing me to look for alternatives.
Please see below for detailed explanation.
We have a Parent class which does not grow much, the entire dataset has roughly 900 records.
However, the Child class, grows at a rate of 100k records over 15 minutes. It's generating millions of records on a daily basis.
Records are inserted to the child class as an update/add of the parent.
create class Parent extends V
create class Child
Parent data model
{
"id": string,
"name": string,
"rank": integer,
"price_usd": float,
"price_cny": float,
"volume_24h_usd": float
"market_cap_usd": float,
"available_supply": integer,
"total_supply": integer,
"last_updated": datetime,
"MarketName": string,
"Exchange": string,
"last_refresh": datetime
}
Child data model
{
"MarketName": string,
"High": float,
"Low": float,
"Volume": float,
"Last": float,
"Bid": float,
"Ask": float,
"BaseVolume": float,
"TimeStamp": datetime
}
Parent Data Sample
{
"#type": "d",
"#rid": "#506:403225",
"#version": 1,
"#class": "Parent",
"MarketName": "USD-CNY",
"High": 0.00026815,
"Low": 0.00023002,
"Volume": 17005.93615271,
"Last": 0.00026103,
"Bid": 0.00026104,
"Ask": 0.000265,
"BaseVolume": 4.15293493,
"TimeStamp": "2017-07-15T18:28:11.857",
"#fieldTypes": "High=d,Low=d,Volume=d,Last=d,Bid=d,Ask=d,BaseVolume=d"
}
Child record insert
Update Parent add Child = [
{
"#type":"d",
"#class":"Child",
"MarketName":"USD-CNY",
"High":0.000083,
"Low":0.00006815,
"Volume":18688741.88795826,
"Last":0.00006857,
"Bid":0.00006857,
"Ask":0.00006889,
"BaseVolume":1412.08213181,
"TimeStamp":"2017-07-19T17:12:59.44"
}
] where MarketName = "USD-CNY"
Poor performance on following query
select
MarketName,
Last,
Bid,
Ask,
High,
Low,
BaseVolume,
TimeStamp,
TimeStamp.asDateTime().format('yyyy-MM-dd') as date,
TimeStamp.asDateTime().format('hh:mm:ss') as time,
if(eval('TimeStamp.asDateTime().format("hh") between 0 and 11'),'PM','AM') as hour12
from Child where MarketName = "USD-CNY" order by TimeStamp desc
Additional information.
In the Child class, we have roughly 9 million records WHERE MarketName = "USD-CNY"
The execution of this query, takes roughly 33 - 40 seconds.
I have not done any indexing on the parent or child class, need some guidance on proper indexing techniques for a multimodel database.
Also, I am not expecting a response of the 9 million records. I am okay with paginating my results and just getting the top 100.
Any guidance is appreciated.

Like any other DBMS, OrientDB requires an index on the property you're using as a filter. Try executing this:
CREATE INDEX Child.MarketName ON Chile( market name ) UNIQUE
And you will see your query should be <300ms now.
For more information look at https://orientdb.com/docs/2.2/SQL-Create-Index.html.

I'd try this:
CREATE INDEX Child_Market_Time_idx ON Child (Marketname, TimeStamp) UNIQUE;

Related

Find the maximum delta of a field between date A and date B

I have been noodling around with an aggregation for hours now trying to work out how to do this without writing code and walking the collection. There are millions of documents in this collection, so I'd prefer to write an aggregation than walk the entire collection and brute force a result, but I am officially stumped. I am a newbie to MongoDB and aggregations in particular, so please be gentle. I do want to learn, so I'd also appreciate pointers to tutorials or similar to help me improve.
We have a collection that includes updated_at, which is when a document was created, faction_name or faction_id, and system name or system_id, and influence. I am trying to create a sorted aggregation that will list the top faction influence delta changes between two updated_at dates (date A, such as today, and date B, such as yesterday) in the same system and faction. I'd like the output to contain the faction id or name and system id or name, and delta of the two influence values. influence_delta would be a computed value from the difference of two documents, and influence movement can result in a positive or negative change. We believe the largest single day change is 0.075 and the smallest is -0.075.
Basically, I'm trying to create a table in a web app that will display the biggest influence changes between date A and date B, but the system_id and faction_id need to be the same.
system_id
faction_id
influence_delta
605e573a68ad125bce5186b4
605e573a68ad125bce5186bd
0.075
605e573a68ad125bce51868d
605e573a68ad125bce518696
0.031
605e573a68...
605e573a68ad...
0.021
Here's a sample document. There will be at least one document per day for popular systems, and for less popular systems, it could be weeks since a document was last recorded. For each system and faction, there be the same faction_id and system_id values as long as the faction has not arrived recently or retreated (this is Elite Dangerous), and there will be different influence values. Stored influence values range from 0.0 to 1.0. I would suggest for performance, please consider using system_id and faction_id, which are unique and indexed, rather than the system or faction name.
{
"_id": {
"$oid": "605e573bbfcfe2a2cdb7fefb"
},
"updated_at": {
"$date": "2021-03-26T21:50:50.000Z"
},
"updated_by": "EDDN",
"system": "Gliese 875",
"system_lower": "gliese 875",
"system_id": {
"$oid": "605e573a68ad125bce5186b4"
},
"faction_id": {
"$oid": "605e573a68ad125bce5186bd"
},
"faction_name": "Gliese 875 Allied Exchange",
"faction_name_lower": "gliese 875 allied exchange",
"state": "none",
"influence": 0.039715,
"happiness": "$faction_happinessband2;",
"active_states": [],
"pending_states": [],
"recovering_states": [],
"conflicts": [],
"systems": [
{
"system_id": {
"$oid": "605e573a68ad125bce5186b4"
},
"name": "Gliese 875",
"name_lower": "gliese 875"
}
],
"__v": 0
}

How can I do less than, greater than in JSON array object Postgres fields? But performance is much better required

I want to retrieve data by specific field operation it store array of object. i want to add new object in it.
CREATE TABLE justjson ( id INTEGER, doc JSONB);
INSERT INTO justjson VALUES ( 1, '[
{
"name": "abc",
"age": "22"
},
{
"name": "def",
"age": "23"
}
]');
retrieve data where age is greater then and equal to 23 how is possible
And i have solution for such thing but it decrease query performance to much.
my solutions is
using jsonb_array_elements:
t=# with a as (select *,jsonb_array_elements(doc) k from justjson)
select k from a where (k->>'age')::int >= 23;
k
------------------------------
{"age": "23", "name": "def"}
(1 row)
I need a solution or other thing by which i do such thing with high performance.

MongoDB performance issues

We are currently using a collection called items which contain 10 million entries in our MongoDB database.
This collection contains (amongst many others) two columns named title and country_code. One such entry looks like this
{
"_id": ObjectId("566acf868fdd29578f35e8db"),
"feed": ObjectId("566562f78fdd2933aac85b42"),
"category": "Mobiles & Tablets",
"title": "360DSC Crystal Clear Transparent Ultra Slim Shockproof TPU Case for Iphone 5 5S (Transparent Pink)",
"URL": "http://www.lazada.co.id/60dsc-crystal-clear-transparent-ultra-slim-shockproof-tpu-case-for-iphone-5-5s-transparent-pink-3235992.html",
"created_at": ISODate("2015-12-11T13:28:38.470Z"),
"barcode": "36834ELAA1XCWOANID-3563358",
"updated_at": ISODate("2015-12-11T13:28:38.470Z"),
"country_code": "ID",
"picture-url": "http://id-live.slatic.net/p/image-2995323-1-product.jpg",
"price": "41000.00"
}
The cardinality on column country_code is very high. We have created two text indices for these columns:
db.items.createIndex({title: "text", country_code: "text"})
In our examples we try to query:
db.items.find({"title": { "$regex": "iphone", "$options": "i" }, country_code: "US"}).limit(10)
A query which takes around 6 seconds to complete, which seems unusually high for this type of database.
Whenever we try a country_code (e.g., country_code: "UK") that has less results, it will return results within milliseconds.
Would there be any particular reason, why these queries differ so much in their time to return results?
EDIT:
All answers here helped so if you have this issue yourself, try all of 3 of the solutions. Could only mark 1 as correct though.
Switch around the order of the fields in your index. Order matters.
db.items.createIndex({country_code: "text", title: "text"})
Ensure you maintain this order when querying:
db.items.find({country_code: "US", "title": { "$regex": "iphone", "$options": "i" }}).limit(10)
What this will do is drastically decrease the amount of title fields you need so search a substring for.
Also as mentioned by #Jaco, you should take advantage of your "text" index. See how to query a text index here.
As you do an exact search on country_code, you can add the text index on title only:
db.items.createIndex({title:"text"})
and add a seperate index on country_code:
db.items.createIndex({country_code:1})
As you have defined a text index on title you don't have to use a regular expression, but instead you can do a text search like this:
db.items.find({$text:{$search:"iphone"},country_code:"US"})
You should build an index like {country_code: 1, title: "text"}.
Equal is much more faster than regular expression, make it count.

MongoDb: how to create the right (composite) index for data with many searchable fields

UPDATE: I need to add that the point of this question is to allow me to define schemas for Json Rest Stores. The user can search by any one key, or several keys. So, I cannot easily predict what the users will search by -- it could be 1, 2, 5 fields (this is especially true for data-rich fields like people, bookings, etc.)
Imagine that I have an index as such:
{ "item": 1, "location": 1, "stock": 1 }
Following the MongoDb manual on indexes:
MongoDB can use this index to support queries that include:
the item field,
the item field and the location field,
the item field and the location field and the stock field, or
only the item and stock fields; however, this index would be less efficient than an index on only item and stock.
MongoDB cannot use this index to support queries that include:
only the location field,
only the stock field, or
only the location and stock fields.
Now, suppose I have a schema with exactly these fields:
item: String
location: String
stock: String
qty: number
And imagine I want to make sure every query is indeed indexed. I would do:
For item:
item, location, stock, qty
item, location, qty, stock
item, stock, qty, location
item, stock, location, qty
item, qty, location, stock
item, qty, stock, location
For location:
...you know the gist
Now... this seems a little insane. If you have a database where you have TEN searchable fields, this becomes clearly unworkable as the number of indexes grows exponentially.
Am I missing something? My idea was to define a schema, define which fields were searchable, and write a function that makes up all of the needed indexes regardless of what fields were present and what fields weren't. However, I am thinking about it, and... well, I must be missing something.
Am I?
I will try to explain what does this mean by example. The indexes based on B-tree is not something mongodb specific. In contrast it is rather common concept.
So when you create an index - you show the database an easier way to find something. But this index is stored somewhere with a pointer pointing to a location of the original document. This information is ordered and you might look at it as binary tree which has a really nice property: the search is reduced from O(n) (linear scan) to O(log(n)). Which is much much faster because each time we trim our space in half (potentially we can reduce the time from 10^6 to 20 lookups). For example we have a big collection with field {a : some int, b: 'some other things'} and if we index it by a, we end up with another data structure which is sorted by a. It looks this way (by this I do not mean that it is another collection, this is just for demonstration):
{a : 1, pointer: to the field with a = 1}, // if a is the smallest number in the starting collection
...
{a : 999, pointer: to the field with a = 990} // assuming that 999 is the biggest field
So right now we are searching for a field a = 18. Instead of going one by one through all elements we take something in the middle and if it is bigger then 18, then we are dividing the lower part in half and checking the element there. We continue till we will find a = 18. Then we look at the pointer and knowing it we extract the original field.
The situation with compound index is similar (instead of ordering by one element we order by many). For example you have a collection:
{ "item": 5, "location": 1, "stock": 3, 'a lot of other fields' } // was stored at position 5 on the disk
{ "item": 1, "location": 3, "stock": 1, 'a lot of other fields' } // position 1 on the disk
{ "item": 2, "location": 5, "stock": 7, 'a lot of other fields' } // position 3 on the disk
... huge amount of other data
{ "item": 1, "location": 1, "stock": 1, 'a lot of other fields' } // position 9 on the disk
{ "item": 1, "location": 1, "stock": 2, 'a lot of other fields' } // position 7 on the disk
and want an index { "item": 1, "location": 1, "stock": 1 }. The lookup table would look like this (one more time - this is not another collection, this is just for demonstration):
{ "item": 1, "location": 1, "stock": 1, pointer = 9 }
{ "item": 1, "location": 1, "stock": 2, pointer = 7 }
{ "item": 1, "location": 3, "stock": 1, pointer = 1 }
{ "item": 2, "location": 5, "stock": 7, pointer = 3 }
.. huge amount of other data (but not necessarily here. If item would be one it would be somewhere next to items 1)
{ "item": 5, "location": 1, "stock": 3, pointer = 5 }
See that here everything is basically sorted by item, then by location and then by pointer.
The same way as with a single index we do not need to scan everything. If we have a query which looks for item = 2, location = 5 and stock = 7 we can quickly identify where documents with item = 2 are and then the same way quickly identify where among these items item with location 5 and so on.
And right now an interesting part. Also we created just one index (although this is a compound index, it is still one index) we can use it to quickly find the element
only by the item. Really all we need to do is only the first step. So there is no point to create another index {location : 1} because it is already covered by compound index.
also we can quickly find only by item and by location (we need only 2 steps).
Cool 1 index but helps us in three different ways. But wait a minute: what if we want to find by item and stock. Oh it looks like we can speed up this query as well. We can in log(n) find all elements with specific item and ... here we have to stop - magic has finished. We need to iterate through all of them. But still pretty good.
But may it can help us with other queries. Lets look at a query by location which looks like was already ordered. But if you will look at it - you see that this is a mess. One in the beginning and then one in the end. It can not help you at all.
I hope this clarifies few things:
why indexes are good (reduce time from O(n) to potentially O(log(n))
why compound indexes can help with some queries nonetheless we have not created an index on that particular field and help with some other queries.
what indexes are covered by compound index
why indexes can harm (it creates additional datastructure which should be maintained)
And this should tell another valid thing: index is not a silver bullet. You can not speed up all your queries, so it sound silly to think that by creating indexes on all fields EVERYTHING would be super fast.
What are your real query patterns? It's very unlikely that you would need to create all of these possible index combinations. I also doubt that including qty in the index would be of much use. Do you need to search for things where qty == 4 independent of location and item type?
An index doesn't need to identify every single record, it just needs to be specific enough to make any final scan small. Given an item code or a stock value are there really that many locations that you'd also need to index on them?
I suspect in this case an index on item, an index on location and and index on stock would be sufficient to answer most likely queries with sufficient speed. (But we'd need to know more about what these field names mean and what the count and distribution of values is within them).
Use explain with your queries and you can see how well they are performing. Add indices as necessary, don't create every possible ordering.

How to define a couchdb view that I can filter on attributes of different types of document?

I have two types of document in a couch database. There are Events and Occurences. One Event has many Occurences.
Event:
{
"_id": "49bb92b8896515a2994e524b38a041d3",
"type": "Event",
"eventID": 1234,
"area": "m1"
}
Occurence:
{
"_id": "49bb92b8896515a2994e524b38a041d4",
"type": "Occurence",
"occurenceID": 7890,
"eventID": 1234,
"date": "2013-01-01"
}
I need to find the count of occurences per date filtered by an area name and by a range of dates. In SQL, I'd use this query:
SELECT Date, count(*)
FROM Event INNER JOIN Occurence ON Occurence.EventID = Event.EventID
WHERE Event.Area = "m1"
AND Occurence.Date BETWEEN '2013-01-01' AND '2013-02-01'
GROUP BY Date
I don't mind executing more than one query but my database has over 300,000 occurence documents (and will grow 10 times that), so I need to get the results by tansfering as few documents as possible. The app that queries this couchdb is written with node.js.
Yeah, this would require two queries to get right, I think. You should consider denormalizing by copying the event area into the occurrence documents, that would make it a lot easier.