Discover unique values for a specified JSON attribute among all records in a database

Is it possible to fetch all the unique values of a json-property from multiple documents in a collection using the Marklogic Java Client API?

For example, if there are 3 "MyDocument" type documents with the property "myProperty" as follows:

MyDocument1.json

{
    "myProperty":"val1"
}

MyDocument2.json

{
    "myProperty":"val1"
}

MyDocument3.json

{
    "myProperty":"val2"
}

The goal is to retrieve all unique values for "myProperty", which would be "val1" and "val2".

Additionally, can the documents be grouped based on these distinct values? For instance:

{
    "val1": [
       {
           "myProperty":"val1"
       },
       {
           "myProperty":"val1"
       }
    ],
    "val2": [
       {
           "myProperty":"val2"
       }
    ]
}

Any assistance or guidance in the right direction would be greatly appreciated. Thank you!

Update:

I was able to achieve the desired result using XQuery in qConsole. Here's what I did:

xquery version "1.0-ml";
import module namespace search = "http://marklogic.com/appservices/search" at "/MarkLogic/appservices/search/search.xqy";

let $options :=
    <options xmlns="http://marklogic.com/appservices/search">
        <values name="myProperty">
            <range type="string" facet="true">
                <json-property>myProperty</json-property>
            </range>
        </values>                
    </options>
    
return search:values("myProperty", $options)

The result obtained was:

<search:values-response name="myProperty" type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:search="http://marklogic.com/appservices/search">
    <search:distinct-value frequency="2">val1</search:distinct-value>
    <search:distinct-value frequency="1">val2</search:distinct-value>
</search:values>

Now the aim is to accomplish this using the Java Client API.

Answer №1

To make things easier, you can utilize a range-index on that specific property to extract values from the lexicon using a function like

Alternatively, if needed, you could opt for a more manual approach. This would involve looping through each document, fetching the property value, storing it in a map, and then displaying the keys from the map.

In case you're dealing with a significant number of documents containing the JSON property, attempting to gather all the information in one query might lead to timeouts or Expanded Tree Cache errors. In such situations, running a CoRB job to export the property values to a file and using the EXPORT-FILE-SORT option with either ascending or distinct values can be quite beneficial.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Shortcut for JSON formatting in Sublime Text

I prefer using SublimeText for coding. Is there a quick way to reindent JSON code in SublimeText? I've successfully installed Package Control and it's functioning properly. I attempted to use the JsonReindent package, but couldn't find a ...

Error encountered in Java code execution using MVN JMeter Hashtree

Just started exploring jmeter and I'm attempting to execute an existing JMeter Test from Java code following the guidance I found at the link provided below. https://www.blazemeter.com/blog/5-ways-launch-jmeter-test-without-using-jmeter-gui However, ...

having difficulty sending a post request with Angular

Submitting form data via HTTP post will look like this: saveDataFile(mutlidata,id,value): Observable<Response> { var _url = 'http://xxxx.xxx.xxx'; var saveDataURL = _url + '/' + id; var _this = this; ...

Are there any JavaScript charting tools that can draw in a clockwise direction with multiple data points?

Can anyone recommend a JavaScript live chart/graph library that can create clockwise graphs with multiple points, similar to the example below? https://i.sstatic.net/dQfK4.png ...

Scrolling seamlessly on websites with a single page

I am developing a single-page website that uses different section IDs instead of multiple pages. It's functioning properly, but I want to implement smooth scrolling to the sections rather than just statically jumping to them on the page. Jsfiddle: ht ...

Error: The use of import statement is not allowed outside a module in JavaScript due to a Syntax

I'm just beginning my journey with React, starting from scratch without setting up all the necessary dependencies. Initially, I used CDNs in my html file but now I want to learn how to import React and ReactDOM into my local setup and also link CSS fi ...

Basic inquiry about Ajax

Would you like to know a simple solution for refreshing a specific area of your website using ajax? Instead of having JavaScript constantly checking for changes on the server, is there a way for the server to send data when a certain event occurs? Imagine ...

"What is the process for ASP MVC to return JSON data with a custom variable

Within my application, I have defined a user class. This class includes properties for name, phone number, and address. public class User { public string name { get; set; } public string phone { get; set; } public string address { get; set; } ...

Incorporate CSS file into the head section or directly within the HTML section without the need for JavaScript

I'm facing an issue with adding a CSS file to my webpage using JavaScript code at the bottom of the page. When users disable JavaScript, the file cannot be added. Is there a way to include the CSS file in the page without relying on JavaScript? $(doc ...

Elevate the API level on an Android device while utilizing the compile ('com.google.android.gms:play-services:+') function

Having difficulties reducing the API level below 14 due to the dependencies I am using: dependencies { compile ('com.google.android.gms:play-services:+') compile files('libs/dagger-1.2.2.jar') compile files('libs/jav ...

The issue of a false value not being correctly matched in Jasmine is causing problems

Currently, I am utilizing the following code to evaluate an element with aria-checked="false". expect((accessPolicyPage.listSelectAll).getAttribute("aria-checked")).toEqual("false"); The output is presenting as Expected [ 'false' ] to equal &ap ...

Navigating forwards in Angular 7 causes loss of state

I have a situation with my angular 7 Ionic application. When I navigate to a page, I use the following code snippet: navigateToDetail(entity: User) { const navigationExtras: NavigationExtras = { state: { entity, entityId: entity.id ...

Masking Aadhaar numbers

I need to find a way to detect when the back button is pressed on an input field. The methods I have tried, e.key and e.which, are returning as undefined in mobile Chrome. How can I make this work? It's functioning properly on desktop. jQuery(funct ...

Tips for incorporating personalized form and input directives in AngularJS while addressing issues with transcluded scope

Over the last few days, I attempted to implement something along these lines: %myform(name='somename' ng-controller='whatever') %myinput(ng-model='user.firstName' ... The controller has a user structure with firstName, l ...

jade, express, as well as findings from mysql

My goal is to display the results of an SQL query in Jade, which pulls data from a table of banners. Each banner has a unique id and falls under one of three types. Here is my current code : express : connection.query("SELECT * FROM banner_idx ORDER BY ...

forming an instance from JSON information

In a .json file, I have data that includes information on countries such as their currency, major language, and land area in square kilometers or square miles. { "countries": { "sweden": { "currency": "Swedish krona", " ...

Sending a second request with jQuery to upload a file

After successfully uploading a file using jQuery AJAX along with a progress bar (XHR), the next step involves processing the uploaded file on the server side. To check the status of this server-side processing, I attempt to make another jQuery AJAX request ...

Having issues with implementing PrimeNG components (Directive annotation not detected)

Having difficulty integrating PrimeNG components (beta5) with Angular2 (rc.1). Whenever attempting to utilize a component, such as the menubar, the following error is consistently encountered: No Directive annotation found on Menubar New to Angular and ...

Are there any discussions underway about updating JSON standards to officially permit unquoted property names?

Technically speaking, the following JSON is considered invalid: { color: "blue", size: 14 } This is because according to the specification, property names like "color" and "size" should be enclosed in quotes, like this: { "color": "blue", "size" ...

Passing arguments from an Angular directive to a controller function within an element's HTML

Is there a way to pass the URL of an anchor tag in the directive to the controller function "itemClicked"? The code below successfully logs the "post" object when clicked. HTML: <div ng-repeat="post in posts" > <div find-urls link-clicked="i ...