Something similar to my question here: https://stackoverflow.com/questions/40715822/marklogic-node-js-api-group-by-and-sort-by-count
I have documents in Marklogic with fields name and amount. I want to get the total amount for each name. Basically in SQL it would be
select name, sum(amount) from table group by name
I have range indexes for both name and amount. For getting sum aggregates, the documentation suggests something like valuesBuilder.fromIndexes('amount').aggregates('sum'), but this only gets the sum for all records, instead of per name like I want.
Any advice?
If you enjoyed my content for some reason, I'd love to hear from you! Here are some options:
- You can buy me a coffee!
- Click here to post a comment!
- You can write a reply on your own site and submit the URL as a webmention via the form below.
- Or you can just contact me!
can you show a sample document? I assume that you have the same name appear in different documents with different URIs - is that correct?
I don't think there's an out-of-the-box group by, but you can build an extension to do it. I made some sample docs like this:
I ran this code in Query Console:
That got me a response of:
I think that's what you're looking for. Other stuff you'll need:
name
(string) andcount
(int).As an alternative to Dave's suggestion you can do something similar in Node.js but again, the work/code would have to be developed by you.
Option 1)
this code here creates a value co-occurance of names and amounts - you can then go and process this information.
Option 2)
Get the names from the indexes, then feed that information to another function that would get the amounts and sum them up:
Option 3)
What Dave suggested - create the SJS extension, and call that from Node.js
One footnote to the good suggestions from Tamas and Dave -- in MarkLogic 9, you can use the Optic API in ways similar to the following example (in this case, using Server-Side JavaScript):