Güvener

Filter by color on OpenSearch

Discover visually relevant content that matches a particular color scheme.

Detect dominant color

You can use Sharp Node.js Library to detect dominant color of an image.

const { dominant } = await sharp(img).stats();

After detecting dominant color, we need a color representation at OpenSearch index .

Update index for saving color in HSL representation

We’ll use HSL representation to store dominant colors. This allows us to manipulate hue, saturation, and lightness values individually, giving us more flexibility in adjusting colors. Plus, writing a color search query becomes simpler with the hue range from 0 to 360.

Add nested index to your opensearch index mapping. For example:

put
http://[localhost:9200]/[index]/_mapping/[Mapping_Name]?include_type_name=true|false
{
  "properties": {
    "color":  {
        "properties" : {
            "h" : { "type" : "integer" },
            "s" : { "type" : "integer" },
            "l" : { "type" : "integer" }
        }
    }
  }
}

Write a color search query

Let’s search for blue items in OpenSearch.
Knowing that according to hue wheel, 0 is red, 120 is green, and 240 is blue.

Wheel

We can query items having hue within 240 ± 10 degree.

post
http://[localhost:9200]/[index]/[Mapping_Name]/_search
{
    "query": {
        "bool": {
            "must": [
                {
                    "range": {
                        "color.h": {
                            "gte": 230,
                            "lte": 250
                        }
                    }
                },
                {
                    "range": {
                        "color.s": {
                            "gte": 50,
                            "lte": 90
                        }
                    }
                },
                {
                    "range": {
                        "color.l": {
                            "gte": 50,
                            "lte": 90
                        }
                    }
                }
            ]
        }
    }
}

Utilities

Javascript color conversions such as RGB to HSL, Color conversions in JS.
Color wheel for visual representation, CSS at Codepen.

Conclusion

Using HSL color representation in Opensearch is practical for searching different shades of hue in your index. This approach is storage independent and can also be applied to relational databases with SQL.