mg03
mg03

Reputation: 767

go map search using values in a map

I have a map structured like map[string][]string. Now I have to find all keys which have the required values in the value slice. I can do something like this:

// allsvc is map[string][]string
var newsl []string


    for k, v :=  range  allsvc {
        for _, val := range v {
            if v == "type1" || v == "type2" {
                newsl.append(k)
            }
        }

    }

The map allsvc has atleast a half million entries at any given time, and the lookup is quite frequent. I get the allsvc map as an ouput of a 3rd party library and then I have to search in it using values in my api and provide a response. Given the high frequency of lookup not using keys but with values, the way i have done it makes my api response time to be in the seconds. Is there a way to better performance (speed of lookup)?

Upvotes: 1

Views: 5479

Answers (1)

eugenioy
eugenioy

Reputation: 12393

If you will query that map multiple times, it might be worth spending some time re-arranging it when you get it so that you can then query it faster.

It seems you need to invert the relationships, making the values in allsvc the keys in the new map, and having the keys as values so that you can then just make lookups in the new map.

This can be a way to re-arrange the map:

func arrangeMap(oldMap map[string][]string) map[string][]string {
    newMap := make(map[string][]string)
    for k, v :=  range  oldMap {
        for _, val := range v {
            newMap[val] = append(newMap[val], k)
        }
    }
    return newMap
}

See here a playground showing the idea:

https://play.golang.org/p/0ThZlX9xUn

Upvotes: 2

Related Questions