Skip to content

Instantly share code, notes, and snippets.

@cwurm
Created April 16, 2019 20:06
Show Gist options
  • Save cwurm/cf61f6b4075eac630b60b8292f084146 to your computer and use it in GitHub Desktop.
Save cwurm/cf61f6b4075eac630b60b8292f084146 to your computer and use it in GitHub Desktop.
Elasticsearch nested nested keyword search
# Create new index
PUT test2
{
"mappings": {
"properties": {
"relations": {
"type": "nested",
"properties": {
"parts": {
"type": "nested",
"properties": {
"ACL": {
"type": "keyword"
}
}
}
}
}
}
}
}
# Index first document: red
PUT test2/_doc/1
{
"relations": [
{
"parts": [
{
"ACL": "red"
}
]
}
]
}
# Index second document: RED
PUT test2/_doc/2
{
"relations": [
{
"parts": [
{
"ACL": "RED"
}
]
}
]
}
# Index third document: rEd
PUT test2/_doc/3
{
"relations": [
{
"parts": [
{
"ACL": "TEST"
}
]
}
]
}
# Search for "RED" - finds only first document.
GET test2/_search
{
"query": {
"nested": {
"path": "relations",
"query": {
"nested": {
"path": "relations.parts",
"query": {
"term": {
"relations.parts.ACL": {
"value": "RED"
}
}
}
}
}
}
}
}
@cwurm
Copy link
Author

cwurm commented Apr 16, 2019

# Search using multiple terms - finds 2 out of 3 documents.
GET test2/_search
{
  "query": {
    "nested": {
      "path": "relations",
      "query": {
        "nested": {
          "path": "relations.parts",
          "query": {
            "terms": {
              "relations.parts.ACL": [
                "RED",
                "red"
              ]
            }
          }
        }
      }
    }
  }
}

@cwurm
Copy link
Author

cwurm commented Apr 16, 2019

# Create new index
PUT test3
{
  "mappings": {
    "properties": {
      "relations": {
        "properties": {
          "parts": {
            "properties": {
              "ACL": {
                "type": "keyword"
              }
            }
          }
        }
      }
    }
  }
}

# Index first document: red
PUT test3/_doc/1
{
  "relations": {
    "parts": {
       "ACL": "red" 
    }
  }
}

# Index second document: RED
PUT test3/_doc/2
{
  "relations": {
    "parts": {
       "ACL": "RED" 
    }
  }
}

# Index third document: rEd
PUT test3/_doc/3
{
  "relations": {
    "parts": {
       "ACL": "rEd" 
    }
  }
}

# Check 3 documents exist
GET test3/_search

# Search for "RED" - finds only first document.
GET test3/_search
{
  "query": {
    "terms": {
      "relations.parts.ACL": [
        "RED"
      ]
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment