英文:
go map search using values in a map
问题
我有一个结构为map[string][]string的地图。现在我必须找到所有具有所需值的键,这些值在值切片中。我可以这样做:
// allsvc是map[string][]string
var newsl []string
for k, v := range allsvc {
for _, val := range v {
if val == "type1" || val == "type2" {
newsl = append(newsl, k)
}
}
}
在任何给定时间,map allsvc至少有50万个条目,并且查找非常频繁。我将allsvc地图作为第三方库的输出,并且我必须使用我的API中的值在其中进行搜索并提供响应。由于查找的频率很高,不使用键而是使用值,所以我所做的方式使得我的API响应时间为几秒钟。有没有一种更好的性能(查找速度)的方法?
英文:
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)?
答案1
得分: 2
如果您要多次查询该地图,那么在获取地图后重新排列它可能是值得的,这样您就可以更快地查询它。
看起来您需要反转关系,将allsvc
中的值作为新地图中的键,并将键作为值,这样您就可以在新地图中进行查找。
这是重新排列地图的一种方法:
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
}
在这里可以看到一个演示这个想法的示例:
https://play.golang.org/p/0ThZlX9xUn
英文:
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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论