Elastica\Type::addDocument PHP Method

addDocument() public method

Adds the given document to the search index.
public addDocument ( Document $doc ) : Response
$doc Document Document with data
return Response
    public function addDocument(Document $doc)
    {
        $path = urlencode($doc->getId());
        $type = Request::PUT;
        // If id is empty, POST has to be used to automatically create id
        if (empty($path)) {
            $type = Request::POST;
        }
        $options = $doc->getOptions(['version', 'version_type', 'routing', 'percolate', 'parent', 'ttl', 'timestamp', 'op_type', 'consistency', 'replication', 'refresh', 'timeout']);
        $response = $this->request($path, $type, $doc->getData(), $options);
        $data = $response->getData();
        // set autogenerated id to document
        if (($doc->isAutoPopulate() || $this->getIndex()->getClient()->getConfigValue(['document', 'autoPopulate'], false)) && $response->isOk()) {
            if (!$doc->hasId()) {
                if (isset($data['_id'])) {
                    $doc->setId($data['_id']);
                }
            }
            if (isset($data['_version'])) {
                $doc->setVersion($data['_version']);
            }
        }
        return $response;
    }

Usage Example

 public function testSearch()
 {
     $client = $this->_getClient();
     $index = new Index($client, 'test');
     $index->create(array(), true);
     $type = new Type($index, 'helloworld');
     $doc = new Document(1, array('id' => 1, 'email' => '*****@*****.**', 'username' => 'hans', 'test' => array('2', '3', '5')));
     $type->addDocument($doc);
     $doc = new Document(2, array('id' => 2, 'email' => '*****@*****.**', 'username' => 'emil', 'test' => array('1', '3', '6')));
     $type->addDocument($doc);
     $doc = new Document(3, array('id' => 3, 'email' => '*****@*****.**', 'username' => 'ruth', 'test' => array('2', '3', '7')));
     $type->addDocument($doc);
     // Refresh index
     $index->refresh();
     $boolQuery = new Bool();
     $termQuery1 = new Term(array('test' => '2'));
     $boolQuery->addMust($termQuery1);
     $resultSet = $type->search($boolQuery);
     $this->assertEquals(2, $resultSet->count());
     $termQuery2 = new Term(array('test' => '5'));
     $boolQuery->addMust($termQuery2);
     $resultSet = $type->search($boolQuery);
     $this->assertEquals(1, $resultSet->count());
     $termQuery3 = new Term(array('username' => 'hans'));
     $boolQuery->addMust($termQuery3);
     $resultSet = $type->search($boolQuery);
     $this->assertEquals(1, $resultSet->count());
     $termQuery4 = new Term(array('username' => 'emil'));
     $boolQuery->addMust($termQuery4);
     $resultSet = $type->search($boolQuery);
     $this->assertEquals(0, $resultSet->count());
 }
All Usage Examples Of Elastica\Type::addDocument