Search code examples
solrsolr-query-syntaxsolr8

Solr query for child documents and return parents and filtered children


I'm having trouble creating a Solr query to be able to pull out the right documents, and am starting to wonder if what I am trying to do is even possible.

Currently on Solr 8.9 using a managed schema and every field is using a wildcard field.

Firstly what the document looks like

(changed names due to redacting internal business language):


{
  "id": "COUNTY:1",
  "county_name_s": "Hertfordshire",
  "coordinates_s": {
    "id": "COUNTY:1COORDINATES:!",
    "lat_s": "54.238948",
    "long_s": "54.238948"
  },
  "cities": [
    {
      "id": "COUNTY:1CITY:1",
      "city_name_s": "St Albans",
      "size": {
        "id": "COUNTY:1CITY:1SIZE:1",
        "sq_ft_s": "100",
        "sq_meters_s": "5879"
      }
    },
    {
      "id": "COUNTY:1CITY:2",
      "city_name_s": "Watford",
      "size": {
        "id": "COUNTY:1CITY:2SIZE:2",
        "sq_ft_s": "150",
        "sq_meters_s": "10000"
      }
    }
  ],
  "mayor": {
    "title_s": "Mrs.",
    "first_name_s": "Sheila",
    "last_name_s": "Smith"
  }
}

And what I want to return:

{
  "id": "COUNTY:1",
  "county_name_s": "Hertfordshire",
  "coordinates": {
    "id": "COUNTY:1COORDINATES:!",
    "lat_s": "54.238948",
    "long_s": "54.238948"
  },
  "cities": [
    {
      "id": "COUNTY:1CITY:1",
      "city_name_s": "St Albans",
      "size": {
        "id": "COUNTY:1CITY:1SIZE:1",
        "sq_ft_s": "100",
        "sq_meters_s": "5879"
      }
    }
  ],
  "mayor": {
    "title_s": "Mrs.",
    "first_name_s": "Sheila",
    "last_name_s": "Smith"
  }
}

Basically my goal is to return more or less the entire thing, however with filtering out one of the cities. For example, the condition for the city would be like city_name_s:"St Albans". So it's to say that I want the parent and all children, however if the child is in that array (ie cities array), then the given field (city_name_s) must equal my defined value, or we don't want that child.

Things I've tried:

I've basically tried two approaches here:

  1. I've tried to play around with {!child} and {!parent} to get a result that I want. Currently I can only get something from City level or the entire thing as if the filter was not there at county level.

  2. I've tried to change values for the childFilter option, with things like:

    • city_name_s:"St Albans" OR (*:* NOT city_name_s:[* TO *]) to try and say 'if field exists it should be this'.

Anyhow I'm starting to run out of ideas with this; been hacking away at it for the past couple of days and not really got any closer.

Thanks in advance for any help; bashing my head against the wall currently so any suggestions are more than welcome :)


Solution

  • I had a similar issue in solr 9.0.0 and this solved it for me: Apache Solr Filter on Child Documents

    In your case, just add fl=*,[child childFilter=city_name_s:"St Albans"]