2017-07-28 102 views
0

我想以我不会有重复的方式在我的文档中存储标签。Elasticsearch:存储无重复标签

我的文档有Tags场定义为:

... 
"Tags": { "type": "string" } 
... 

我从Python中添加标签的Tags领域:

es.update(index=ES_INDEX, doc_type=ES_DOC_TYPE, id=user_id, body=doc) 

我的更新文档:

doc = { 
    "script": { 
    "lang": "groovy", 
    "inline": "ctx._source.Tags.addAll(tags)", 
    "params": { 
     "tags": [ 
     "c#", 
     "winforms", 
     "type-conversion", 
     "decimal", 
     "opacity" 
     ] 
    } 
    } 
} 

这可行,但标签可能是杜折襞。

我想在存储它们之前对标记进行重复数据删除。我基本上想要Tags字段作为一个集合。

这是我试了一下(基于这样的回答:https://stackoverflow.com/a/17465831/318557

... 
"inline": "ctx._source.Tags.addAll(tags); ctx._source.Tags.unique();", 
... 

但它没有任何效果。

有没有Groovy解决方案来做到这一点?或者也许从Elasticsearch的一些支持存储集?

回答

0

问题是在初始化阵列上使用.addAll()。使用REST客户给了我这个消息:

{ 
    "error": { 
    "root_cause": [ 
     { 
     "type": "remote_transport_exception", 
     "reason": "[DevHunt][192.168.1.98:9300][indices:data/write/update[s]]" 
     } 
    ], 
    "type": "illegal_argument_exception", 
    "reason": "failed to execute script", 
    "caused_by": { 
     "type": "script_exception", 
     "reason": "error evaluating ctx._source.Tags.addAll(tags);", 
     "script_stack": [], 
     "script": "", 
     "lang": "groovy", 
     "caused_by": { 
     "type": "null_pointer_exception", 
     "reason": "Cannot invoke method addAll() on null object" 
     } 
    } 
    }, 
    "status": 400 
} 

的解决方案是使用:

... 
"inline": "if(ctx._source.Tags == null) {ctx._source.Tags = [];}; ctx._source.Tags.addAll(tags); ctx._source.Tags.unique();", 
... 
1

我不认为这是一个常规问题。你在检查正确的物体吗?

我有一个下列文件索引:

{ 
    "_index": "script", 
    "_type": "test", 
    "_id": "AV2Jd1zXM1eNU8lqyoZS", 
    "_score": 1, 
    "_source": { 
     "Tags": [ 
      "tag1", 
      "decimal" 
     ] 
    } 
} 

,并呼吁:

curl -X POST \ 
    http://127.0.0.1:9200/script/test/AV2Jd1zXM1eNU8lqyoZS/_update \ 
    -d '{ 
    "script": { 
    "lang": "groovy", 
    "inline": "ctx._source.Tags.addAll(tags); ctx._source.Tags.unique();", 
    "params": { 
     "tags": [ 
     "c#", 
     "winforms", 
     "type-conversion", 
     "decimal", 
     "opacity", 
     "aaa", 
     "aaa" 
     ] 
    } 
    } 
}' 

结果:

{ 
    "_index": "script", 
    "_type": "test", 
    "_id": "AV2Jd1zXM1eNU8lqyoZS", 
    "_score": 1, 
    "_source": { 
     "Tags": [ 
      "tag1", 
      "decimal", 
      "c#", 
      "winforms", 
      "type-conversion", 
      "opacity", 
      "aaa" 
     ] 
} 

所以常规的作品在这里很好,自己与一些REST客户端检查。你可以尝试重新分配集合:

"inline": "ctx._source.Tags = ctx._source.Tags.unique(); ctx._source.Tags += tags.unique();", 

也许这是更多的Python代码的问题?