Elastica\Tool\CrossIndex::copy PHP Method

copy() public static method

Copies type mappings and documents from an old index to a new index.
See also: Elastica\Tool\CrossIndex::reindex()
public static copy ( Index $oldIndex, Index $newIndex, array $options = [] ) : Index
$oldIndex Elastica\Index
$newIndex Elastica\Index
$options array keys: CrossIndex::OPTION_* constants
return Elastica\Index The new index object
    public static function copy(Index $oldIndex, Index $newIndex, array $options = [])
    {
        // normalize types to array of string
        $types = [];
        if (isset($options[self::OPTION_TYPE])) {
            $types = $options[self::OPTION_TYPE];
            $types = is_array($types) ? $types : [$types];
            $types = array_map(function ($type) {
                if ($type instanceof Type) {
                    $type = $type->getName();
                }
                return (string) $type;
            }, $types);
        }
        // copy mapping
        foreach ($oldIndex->getMapping() as $type => $mapping) {
            if (!empty($types) && !in_array($type, $types, true)) {
                continue;
            }
            $type = new Type($newIndex, $type);
            $type->setMapping($mapping['properties']);
        }
        // copy documents
        return self::reindex($oldIndex, $newIndex, $options);
    }

Usage Example

 /**
  * Test default copy.
  *
  * @group functional
  */
 public function testCopy()
 {
     $oldIndex = $this->_createIndex(null, true, 2);
     $newIndex = $this->_createIndex(null, true, 2);
     $oldType = $oldIndex->getType('copy_test');
     $oldMapping = array('name' => array('type' => 'string', 'store' => true));
     $oldType->setMapping($oldMapping);
     $docs = $this->_addDocs($oldType, 10);
     // mapping
     $this->assertInstanceOf('Elastica\\Index', CrossIndex::copy($oldIndex, $newIndex));
     $newMapping = $newIndex->getType('copy_test')->getMapping();
     if (!isset($newMapping['copy_test']['properties']['name'])) {
         $this->fail('could not request new mapping');
     }
     $this->assertEquals($oldMapping['name'], $newMapping['copy_test']['properties']['name']);
     // document copy
     $this->assertEquals(10, $newIndex->count());
     $newIndex->deleteDocuments($docs);
     // ignore mapping
     $ignoredType = $oldIndex->getType('copy_test_1');
     $this->_addDocs($ignoredType, 10);
     CrossIndex::copy($oldIndex, $newIndex, array(CrossIndex::OPTION_TYPE => $oldType));
     $this->assertFalse($newIndex->getType($ignoredType->getName())->exists());
     $this->assertEquals(10, $newIndex->count());
 }
CrossIndex