3

What's the correct way to select a value from an array of objects?

Would like to retrieve a distinct list of the comments.

[
  "comment 1",
  "comment 2",
  "comment 3",
  "comment 4"
]

Current N1QL query

SELECT links[*].comment FROM `my-db`
WHERE type = "links" AND ANY l IN links SATISFIES l.comment IS NOT MISSING END

Results

[
  {
    "comment": [
      "comment 1"
    ]
  },
  {
    "comment": [
      "comment 1",
      "comment 2"
    ]
  },
  {
    "comment": [
      "comment 3",
      "comment 4"
    ]
  }
]

Given a series of documents that contain a comment field:

{
  "type": "links",
  "links": [
    {
      "comment": "comment 1"
    }
  ]
}

{
  "type": "links",
  "links": [
    {
      "comment": "comment 1"
    },
    {
      "comment": "comment 2"
    }
  ]
}

{
  "type": "links",
  "links": [
    {
      "comment": "comment 3"
    },
    {
      "comment": "comment 4"
    }
  ]
}

1 Answer 1

5

Use UNNEST

SELECT DISTINCT RAW l.comment 
FROM `my-db` AS m
UNNEST m.links AS l
WHERE m.type = "links" AND l.comment IS NOT NULL;

OR

If data set is not too large.

SELECT RAW  ARRAY_DISTINCT(ARRAY_FLATTEN(ARRAY_AGG(m.links[*].comment) ,2))
FROM `my-db` AS m
WHERE m.type = "links";
Sign up to request clarification or add additional context in comments.

2 Comments

Both methods above return the expected results. The second did have a double nesting of array (eg. [ [ 'comment 1', 'comment 2' ] ] ) but that's easy to resolve in parsing. With the recommended index applied, both have response times of ~15ms.
change ARRAY_FLATTEN() second argument to 2 and try

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.