Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize Chunkstore mongo read query #851

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 22 additions & 15 deletions arctic/chunkstore/chunkstore.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,22 +262,29 @@ def read(self, symbol, chunk_range=None, filter_data=True, **kwargs):
if chunk_range is not None:
spec.update(chunker.to_mongo(chunk_range))

by_start_segment = [(SYMBOL, pymongo.ASCENDING),
(START, pymongo.ASCENDING),
(SEGMENT, pymongo.ASCENDING)]
segment_cursor = self._collection.find(spec, sort=by_start_segment)

chunks = defaultdict(list)
for _, segments in groupby(segment_cursor, key=lambda x: (x[START], x[SYMBOL])):
segments = list(segments)
mdata = self._mdata.find_one({SYMBOL: segments[0][SYMBOL],
START: segments[0][START],
END: segments[0][END]})

# when len(segments) == 1, this is essentially a no-op
# otherwise, take all segments and reassemble the data to one chunk
chunk_data = b''.join([doc[DATA] for doc in segments])
chunks[segments[0][SYMBOL]].append({DATA: chunk_data, METADATA: mdata})
# Join metadata collection to top level collection on "sym" and "s"(start)
joined = self._collection.aggregate([
{'$match': spec},
{'$lookup': {
'from': self._mdata.name,
'let': {'symbol': '${}'.format(SYMBOL),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I forget, are we still supporting python 2.7? If not, can we use f-strings here?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@TomTaylorLondon - assuming you're using something like this in your code, the comment above is for you

'start': '${}'.format(START)},
'pipeline': [
{'$match': {
'$expr': {
'$and': [{'$eq': ['${}'.format(SYMBOL), '$$symbol']},
{'$eq': ['${}'.format(START), '$$start']}]}}},
{'$project': {'_id': 0, 'm': 0}}],
'as': METADATA}},
{'$sort': {START: 1,
SEGMENT: 1}}],
allowDiskUse=True) # mongo aggregate pipeline stages have a 100MB RAM limit so we enable this flag to handle larger datasets

for (_, sym), segment in groupby(joined, key=lambda x: (x[START], x[SYMBOL])):
segment = list(segment)
chunks[sym].append({DATA: b''.join([doc[DATA] for doc in segment]),
METADATA: segment[0][METADATA][0]})

skip_filter = not filter_data or chunk_range is None

Expand Down