Hello, I need a fast and simple search for an object by field value, like in a database.
for example,
search for an object with the maximum field value,
search by object field value
search object with next value up
What data structure can i use for this?
May be i should create a list or dict for searching fields?
Put your objects in a array and use findfirst, findmax etc. If you need better than O(n), you’ll something else, such as a tree.
1 Like
Databases are fast because they index various columns then can use those index to find the correct row (object) in the database quickly. I haven’t really run into any package that maintains multiple indexes on a set of objects so you can quickly find the object you want based on some criteria.
You could probably create a custom object using the structures in:
Something like:
using DataStructures
struct Foo
value1::Int64
value2::Float64
end
struct Collection
data::Vector{Foo}
lookup1::SortedDict{Int64, Int}
lookup2::SortedDict{Float64, Int}
end
function Base.push!(c::Collection, v::Foo)
if haskey(c.lookup1, v.value1) || haskey(c.lookup2, v.value2)
throw("Foo is not unique")
end
push!(c.data, v)
c.lookup1[v.value1] = length(c.data)
c.lookup2[v.value2] = length(c.data)
end
function highest_value1(c::Collection)
return c.data[last(c.lookup1)]
end
function lowest_value1(c::Collection)
return c.data[first(c.lookup1)]
end
You would have to take a look at the documentation of Datastructures.jl it gives you methods to iterate over the SortedDict objects in key order.
3 Likes