本文整理汇总了Golang中github.com/lytics/cayley/graph.Iterator类的典型用法代码示例。如果您正苦于以下问题:Golang Iterator类的具体用法?Golang Iterator怎么用?Golang Iterator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Iterator类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: iterated
func iterated(it graph.Iterator) []int {
var res []int
for graph.Next(it) {
res = append(res, it.Result().(int))
}
return res
}
示例2: OptimizeIterator
func (qs *QuadStore) OptimizeIterator(it graph.Iterator) (graph.Iterator, bool) {
switch it.Type() {
case graph.LinksTo:
return qs.optimizeLinksTo(it.(*iterator.LinksTo))
}
return it, false
}
示例3: iteratedQuads
func iteratedQuads(qs graph.QuadStore, it graph.Iterator) []quad.Quad {
var res ordered
for graph.Next(it) {
res = append(res, qs.Quad(it.Result()))
}
sort.Sort(res)
return res
}
示例4: iteratedNames
func iteratedNames(qs graph.QuadStore, it graph.Iterator) []string {
var res []string
for graph.Next(it) {
res = append(res, qs.NameOf(it.Result()))
}
sort.Strings(res)
return res
}
示例5: OutputQueryShapeForIterator
func OutputQueryShapeForIterator(it graph.Iterator, qs graph.QuadStore, outputMap map[string]interface{}) {
s := &queryShape{
qs: qs,
nodeID: 1,
}
node := s.MakeNode(it.Clone())
s.AddNode(node)
outputMap["nodes"] = s.nodes
outputMap["links"] = s.links
}
示例6: moveTagsTo
// moveTagsTo() gets the tags for all of the src's subiterators and the
// src itself, and moves them to dst.
func moveTagsTo(dst graph.Iterator, src *And) {
tags := src.getSubTags()
for _, tag := range dst.Tagger().Tags() {
if _, ok := tags[tag]; ok {
delete(tags, tag)
}
}
dt := dst.Tagger()
for k := range tags {
dt.Add(k)
}
}
示例7: TestIterators
func TestIterators(t *testing.T) {
glog.Info("\n-----------\n")
inst, opts, err := createInstance()
defer inst.Close()
if err != nil {
t.Fatalf("failed to create instance: %v", err)
}
qs, _, _ := makeTestStore(simpleGraph, opts)
if qs.Size() != 11 {
t.Fatal("Incorrect number of quads")
}
var expected = []string{
quad.Quad{"C", "follows", "B", ""}.String(),
quad.Quad{"C", "follows", "D", ""}.String(),
}
it := qs.QuadIterator(quad.Subject, qs.ValueOf("C"))
if got, ok := compareResults(qs, it, expected); !ok {
t.Errorf("Unexpected iterated result, got:%v expect:%v", got, expected)
}
// Test contains
it = qs.QuadIterator(quad.Label, qs.ValueOf("status_graph"))
gqs := qs.(*QuadStore)
key := gqs.createKeyForQuad(quad.Quad{"G", "status", "cool", "status_graph"})
token := &Token{quadKind, key.StringID()}
if !it.Contains(token) {
t.Error("Contains failed")
}
// Test cloning an iterator
var it2 graph.Iterator
it2 = it.Clone()
x := it2.Describe()
y := it.Describe()
if x.Name != y.Name {
t.Errorf("Iterator Clone was not successful got: %v, expected: %v", x.Name, y.Name)
}
}
示例8: iterateResults
func iterateResults(qs graph.QuadStore, it graph.Iterator) []string {
var res []string
for graph.Next(it) {
v := it.Result()
if t, ok := v.(*Token); ok && t.Kind == nodeKind {
res = append(res, qs.NameOf(it.Result()))
} else {
res = append(res, qs.Quad(it.Result()).String())
}
}
sort.Strings(res)
it.Reset()
return res
}
示例9: buildInOutIterator
func buildInOutIterator(obj *otto.Object, qs graph.QuadStore, base graph.Iterator, isReverse bool) graph.Iterator {
argList, _ := obj.Get("_gremlin_values")
if argList.Class() != "GoArray" {
glog.Errorln("How is arglist not an array? Return nothing.", argList.Class())
return iterator.NewNull()
}
argArray := argList.Object()
lengthVal, _ := argArray.Get("length")
length, _ := lengthVal.ToInteger()
var predicateNodeIterator graph.Iterator
if length == 0 {
predicateNodeIterator = qs.NodesAllIterator()
} else {
zero, _ := argArray.Get("0")
predicateNodeIterator = buildIteratorFromValue(zero, qs)
}
if length >= 2 {
var tags []string
one, _ := argArray.Get("1")
if one.IsString() {
tags = append(tags, one.String())
} else if one.Class() == "Array" {
tags = stringsFrom(one.Object())
}
for _, tag := range tags {
predicateNodeIterator.Tagger().Add(tag)
}
}
in, out := quad.Subject, quad.Object
if isReverse {
in, out = out, in
}
lto := iterator.NewLinksTo(qs, base, in)
and := iterator.NewAnd(qs)
and.AddSubIterator(iterator.NewLinksTo(qs, predicateNodeIterator, quad.Predicate))
and.AddSubIterator(lto)
return iterator.NewHasA(qs, and, out)
}
示例10: runIteratorToArray
func (wk *worker) runIteratorToArray(it graph.Iterator, limit int) []map[string]string {
output := make([]map[string]string, 0)
n := 0
it, _ = it.Optimize()
for {
select {
case <-wk.kill:
return nil
default:
}
if !graph.Next(it) {
break
}
tags := make(map[string]graph.Value)
it.TagResults(tags)
output = append(output, wk.tagsToValueMap(tags))
n++
if limit >= 0 && n >= limit {
break
}
for it.NextPath() {
select {
case <-wk.kill:
return nil
default:
}
tags := make(map[string]graph.Value)
it.TagResults(tags)
output = append(output, wk.tagsToValueMap(tags))
n++
if limit >= 0 && n >= limit {
break
}
}
}
it.Close()
return output
}
示例11: runIteratorToArrayNoTags
func (wk *worker) runIteratorToArrayNoTags(it graph.Iterator, limit int) []string {
output := make([]string, 0)
n := 0
it, _ = it.Optimize()
for {
select {
case <-wk.kill:
return nil
default:
}
if !graph.Next(it) {
break
}
output = append(output, wk.qs.NameOf(it.Result()))
n++
if limit >= 0 && n >= limit {
break
}
}
it.Close()
return output
}
示例12: optimizeOrder
// optimizeOrder(l) takes a list and returns a list, containing the same contents
// but with a new ordering, however it wishes.
func (it *And) optimizeOrder(its []graph.Iterator) []graph.Iterator {
var (
// bad contains iterators that can't be (efficiently) nexted, such as
// graph.Optional or graph.Not. Separate them out and tack them on at the end.
out, bad []graph.Iterator
best graph.Iterator
bestCost = int64(1 << 62)
)
// Find the iterator with the projected "best" total cost.
// Total cost is defined as The Next()ed iterator's cost to Next() out
// all of it's contents, and to Contains() each of those against everyone
// else.
for _, root := range its {
if _, canNext := root.(graph.Nexter); !canNext {
bad = append(bad, root)
continue
}
rootStats := root.Stats()
cost := rootStats.NextCost
for _, f := range its {
if _, canNext := f.(graph.Nexter); !canNext {
continue
}
if f == root {
continue
}
stats := f.Stats()
cost += stats.ContainsCost * (1 + (rootStats.Size / (stats.Size + 1)))
}
cost *= rootStats.Size
if glog.V(3) {
glog.V(3).Infoln("And:", it.UID(), "Root:", root.UID(), "Total Cost:", cost, "Best:", bestCost)
}
if cost < bestCost {
best = root
bestCost = cost
}
}
if glog.V(3) {
glog.V(3).Infoln("And:", it.UID(), "Choosing:", best.UID(), "Best:", bestCost)
}
// TODO(barakmich): Optimization of order need not stop here. Picking a smart
// Contains() order based on probability of getting a false Contains() first is
// useful (fail faster).
// Put the best iterator (the one we wish to Next()) at the front...
out = append(out, best)
// ... push everyone else after...
for _, it := range its {
if _, canNext := it.(graph.Nexter); !canNext {
continue
}
if it != best {
out = append(out, it)
}
}
// ...and finally, the difficult children on the end.
return append(out, bad...)
}
示例13: TestIterator
func TestIterator(t *testing.T) {
tmpDir, err := ioutil.TempDir(os.TempDir(), "cayley_test")
if err != nil {
t.Fatalf("Could not create working directory: %v", err)
}
defer os.RemoveAll(tmpDir)
t.Log(tmpDir)
err = createNewLevelDB(tmpDir, nil)
if err != nil {
t.Fatal("Failed to create LevelDB database.")
}
qs, err := newQuadStore(tmpDir, nil)
if qs == nil || err != nil {
t.Error("Failed to create leveldb QuadStore.")
}
w, _ := writer.NewSingleReplication(qs, nil)
w.AddQuadSet(makeQuadSet())
var it graph.Iterator
it = qs.NodesAllIterator()
if it == nil {
t.Fatal("Got nil iterator.")
}
size, exact := it.Size()
if size <= 0 || size >= 20 {
t.Errorf("Unexpected size, got:%d expect:(0, 20)", size)
}
if exact {
t.Errorf("Got unexpected exact result.")
}
if typ := it.Type(); typ != graph.All {
t.Errorf("Unexpected iterator type, got:%v expect:%v", typ, graph.All)
}
optIt, changed := it.Optimize()
if changed || optIt != it {
t.Errorf("Optimize unexpectedly changed iterator.")
}
expect := []string{
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"follows",
"status",
"cool",
"status_graph",
}
sort.Strings(expect)
for i := 0; i < 2; i++ {
got := iteratedNames(qs, it)
sort.Strings(got)
if !reflect.DeepEqual(got, expect) {
t.Errorf("Unexpected iterated result on repeat %d, got:%v expect:%v", i, got, expect)
}
it.Reset()
}
for _, pq := range expect {
if !it.Contains(qs.ValueOf(pq)) {
t.Errorf("Failed to find and check %q correctly", pq)
}
}
// FIXME(kortschak) Why does this fail?
/*
for _, pq := range []string{"baller"} {
if it.Contains(qs.ValueOf(pq)) {
t.Errorf("Failed to check %q correctly", pq)
}
}
*/
it.Reset()
it = qs.QuadsAllIterator()
graph.Next(it)
q := qs.Quad(it.Result())
set := makeQuadSet()
var ok bool
for _, t := range set {
if t.String() == q.String() {
ok = true
break
}
}
if !ok {
t.Errorf("Failed to find %q during iteration, got:%q", q, set)
}
qs.Close()
}
示例14: runIteratorWithCallback
func (wk *worker) runIteratorWithCallback(it graph.Iterator, callback otto.Value, this otto.FunctionCall, limit int) {
n := 0
it, _ = it.Optimize()
if glog.V(2) {
b, err := json.MarshalIndent(it.Describe(), "", " ")
if err != nil {
glog.V(2).Infof("failed to format description: %v", err)
} else {
glog.V(2).Infof("%s", b)
}
}
for {
select {
case <-wk.kill:
return
default:
}
if !graph.Next(it) {
break
}
tags := make(map[string]graph.Value)
it.TagResults(tags)
val, _ := this.Otto.ToValue(wk.tagsToValueMap(tags))
val, _ = callback.Call(this.This, val)
n++
if limit >= 0 && n >= limit {
break
}
for it.NextPath() {
select {
case <-wk.kill:
return
default:
}
tags := make(map[string]graph.Value)
it.TagResults(tags)
val, _ := this.Otto.ToValue(wk.tagsToValueMap(tags))
val, _ = callback.Call(this.This, val)
n++
if limit >= 0 && n >= limit {
break
}
}
}
it.Close()
}
示例15: runIterator
func (wk *worker) runIterator(it graph.Iterator) {
if wk.wantShape() {
iterator.OutputQueryShapeForIterator(it, wk.qs, wk.shape)
return
}
it, _ = it.Optimize()
if glog.V(2) {
b, err := json.MarshalIndent(it.Describe(), "", " ")
if err != nil {
glog.Infof("failed to format description: %v", err)
} else {
glog.Infof("%s", b)
}
}
for {
select {
case <-wk.kill:
return
default:
}
if !graph.Next(it) {
break
}
tags := make(map[string]graph.Value)
it.TagResults(tags)
if !wk.send(&Result{actualResults: tags}) {
break
}
for it.NextPath() {
select {
case <-wk.kill:
return
default:
}
tags := make(map[string]graph.Value)
it.TagResults(tags)
if !wk.send(&Result{actualResults: tags}) {
break
}
}
}
if glog.V(2) {
bytes, _ := json.MarshalIndent(graph.DumpStats(it), "", " ")
glog.V(2).Infoln(string(bytes))
}
it.Close()
}