2016-02-09 18 views
4

我有一個Symfony2項目,我試圖使用Elasticsearch實現搜索功能。Elasticsearch中的可選自親關係

我的問題是,我需要索引一個可選的自我關係的實體。這意味着我的項目實體有一個「父」字段,引用另一個項目。

爲了進行搜索,我想在該「父」字段上創建過濾器。 我的Item.parent是否爲NULL?例如

所以,我使用的是FosElasticaBundle。

這裏是我的映射:

types: 
    Item: 
     mappings: 
      name: 
      children: 
       type: object 
       _parent: 
        type: Item 
      parent: 
       type: object 
     _routing: 
      required: false 
     _parent: 
      type : Item 
      identifier: id 
      property : parent 
     persistence: 
      ... 
      model_to_elastica_transformer: 
       service: core.transformer.item 

和變壓器的作用:

$document = new Document(); 

if (!is_null($item->getParent())) { 
    $document->setParent($item->getParent()->getId()); 
} else { 
    $document->setParent(null); 
} 

return $document; 

而且,當我嘗試創建我的索引(php app/console fos:elastica:populate

此命令返回出現問題以下ResponseException:

index: /traveler/Item caused RoutingMissingException[routing is required for [traveler]/[Item]/[null]] 

你有什麼想法,爲什麼這不起作用?這是做這件事的好方法嗎?

謝謝,

+0

不應該** $ document-> setParent($ item-> getParent() - > getId()); **接收一個對象** $ document-> setParent($ item-> getParent()) ; **? – costa

+0

感謝您的回答。 實際上,問題發生在值爲null時(我嘗試在該方法中手動設置一個id,並且它工作正常)。 – TiPi

+0

我認爲 - > getId()不正確,更改爲'setParent($ item-> getParent())' –

回答

1

因爲我的需求在這種情況下非常簡單,我們設法解決了這個問題。

配置

而是在配置使用_parent場的,我用了一個嵌套屬性。

Item: 
    mappings: 
     children: 
      type: "nested" 
      properties: 
       name: ~ 
     parent: 
      type: "object" 

這是一棵樹,所以孩子和父母的屬性都是項目。 我需要與父值過濾器創建requess(null,則等於什麼......)

請求

所以,我用嵌套在\ Elasitca \過濾器\。

舉例來說,當我需要排除根據兒童的用戶和語言的一些resultats,我可以做到以下幾點:

$nestedFilter = new Nested(); 
$boolFilter = new Bool(); 
$boolAndFilter = new BoolAnd(); 
$boolAndFilter 
    ->setFilters(array(
     new Term(array("children.user.id" => $this->getClient()->getId())), 
     new Term(array("children.other" => $language)) 
    )) 
; 

$nestedFilter 
    ->setFilter($boolAndFilter) 
    ->setPath('children') 
; 

$query = new Filtered(
    $query, 
    new BoolNot($boolFilter->addMust($nestedFilter)) 
); 

我覺得這個解決方案具有侷限性(多層次養育我假設),但爲了這個需要,它可以工作。