Zend_Search_Lucene search in array - zend-framework

Is there a way to store an array as a document field and then query that array?
I've got a collection of items, which are tagged. I'd like to be able to search all items that match for example tags 55 and 67.
How would I achieve this?

First you have to create index file with the data in your array. The documentation covers how to create a new index.
so imagining your array look like
$data = array(
array(
'tag' => '55 67',
'content' => 'Lorem Ipsu 1',
'url' => 'http://foobar.net/content.php?id=1'
),
array(
'tag' => '32 67'
'content' => 'Lorem Ipsu 2',
'url' => 'http://foobar.net/content.php?id=2'
)
);
it would give something like that to create your index
// Create index
$index = Zend_Search_Lucene::create('/data/my-index');
foreach($data as $row){
$doc = new Zend_Search_Lucene_Document();
// Store document URL to identify it in the search results
$doc->addField(Zend_Search_Lucene_Field::Text('url', $row['url']));
// Store document TAGS
$doc->addField(Zend_Search_Lucene_Field::Text('tag', $row['tag']));
// Index document contents
$doc->addField(Zend_Search_Lucene_Field::UnStored('contents', $row['content']));
// Add document to the index
$index->addDocument($doc);
}
finally to query your index file
$index = Zend_Search_Lucene::open('/data/my_index');
$hits = $index->find('tag:55 AND tag:67');
foreach ($hits as $hit) {
echo $hit->score;
echo $hit->url;
echo $hit->tag;
}
Note
I am not really sure why you intend to use Lucene to do such work, if you just want a listing of article matching whatever tag would be more easy to do it with plain SQL queries.
After if want to know how Zend_Search_Lucene works that could be an example

Related

Retrieve the user id who posts a single entry of Gravity Form

Suppose that I know the entry ID ($lead_id), how can I retrieve the user who creates that entry.
I try to
$lead = RGFormsModel::get_lead( $lead_id );
$form = GFFormsModel::get_form_meta( $lead['form_id'] );
$values= array();
foreach( $form['fields'] as $field ) {
$values[$field['id']] = array(
'id' => $field['id'],
'label' => $field['label'],
'value' => $lead[ $field['id'] ],
);
}
But the user data is not there. I check sql database, and the user data is in wp_rg_lead table, not in wp_rg_lead_detail table.
Can anybody please help?
The information in the *_rg_lead table is accessible in the array that's returned by the get_lead function. So
user_id = $lead['created_by']
Also note that it's better to use the Gravity Forms API for retrieving the entry, specifically the get_entry function:
GFAPI::get_entry( $entry_id )
which will return an Entry object.

Convert strings to MongoId in array of objects

We have a collection which stores a list of sub objects:
{
_id: MongoID,
title: 'Some title',
items: [
{
sub_type: 'MongoId'
}
]
}
Annoyingly it turns out we've been storing the item.sub_type as both MongoId Objects and as strings.
I've created a query to find all the string versions: (I'm using a regex as some old items were just numbers instead of Ids, they can be ignored).
$query = array(
'items' => array(
'$elemMatch' => array(
'sub_type' => array(
'$type' => 2,
'$regex' => new MongoRegex('/^[a-f\d]{24}$/i')
)
)
)
);
$results = $mongo->collection->find( $query );
I'm now trying to come up with the best way to convert these to MongoIds. I can easily loop through them in PHP and update them, but this seems like a waste.
Is there a better way of doing this?
I just realised I didn't really understand the question. Here goes an update. This one should do it.
Using mongo console...
db.collection.find({}).forEach(function (x) {
x.items.forEach(function (y) {
y.sub_type = ObjectId(y.sub_type);
});
db.collection.save(x);
});

MongoDB (via Fuelphp): Adding entries on an Array

I would appreciate the help here. For the purpose of this discussion I have an example here (I will use paste bin for the codes):
http://pastebin.com/VPuyKn6W
I am trying to produce this output:
http://pastebin.com/4iMLacRu
I understand that I need to use $push to make this work. But upon testing, it doesn't seem to do anything. I am following the instructions as prescribed in the docs, but instead of using $Id, I am using user_id for finding the document in the collection. Here is my model:
http://pastebin.com/QB94tbZn
Am I misunderstanding something, or I am not using the $push operator properly, or something to do on how I created the document?
After walking outside, I finally got my answer.
public static function create_mongo()
{
$data = array(
'user_id' => '123895',
'First_Name' => 'John',
'Last_name' => 'Doe',
'sites' => array(
array(
'title' => 'Sankaku Complex',
'site' => 'http://sankakucomples.com'
)
)
);
$db = Fuel\Core\Mongo_Db::instance();
$db->insert('test_collection',$data);
}
sites should be an array carrying an array variable.

MongoDB & PHP - Returning a count of a nested array

Imagine I have a MonogDB collection containing documents as follows:
{name: 'Some Name', components: {ARRAY OF ITEMS}}
How can I return the name and the count of items in components?
Do I have to use a map/reduce?
I am using PHP's Mongo extension.
EDIT: Snippet of current code in PHP (working) but I just want count of the components
$fields = array(
'name', 'components'
);
$cursor = $this->collection->find(array(), $fields);
$cursor->sort(array('created_ts' => -1));
if (empty($cursor) == true) {
return array();
} else {
return iterator_to_array($cursor);
}
Thanks,
Jim
You could use map-reduce or you could use a simple group query as follows. Since I am assuming that your name property is a unique key, this should work even though it isn't a reason that you'd normally use the group function:
db.test.group({
key: { name:true },
reduce: function(obj,prev) {
var count = 0;
for(k in obj.components)
count++;
prev.count = count;
},
initial: { count: 0}
});
You mentioned that you have an array of components, but it appears that you are storing components as an object {} and not and array []. That is why I had to add the loop in the reduce function, to count all of the properties of the components object. If it were actually an array then you could simply use the .length property.
In PHP it would look something like this (from the Manual):
$keys = array('name' => 1);
$initial = array('count' => 0);
$reduce =<<<JS
function(obj,prev) {
var count = 0;
for(k in obj.components)
count++;
prev.count = count;
},
JS;
$m = new Mongo();
$db = $m->selectDB('Database');
$coll = $db->selectCollection('Collection');
$data = $coll->group($keys, $initial, $reduce);
Finally, I would strongly suggest that if you are trying to access the count of your components on a regular basis that you store the count as an additional property of the document and update it whenever it changes. If you are attempting to write queries that filter based on this count then you will also be able to add an index on that components property.
You could use db.eval() and write the calculation in JavaScript.
Jim-
These are two separate operations; Unless you want to leverage PHP's count on the results you get which you would then do something like:
$m = new Mongo();
$db = $m->selectDB('yourDB');
$collection = $db->selectCollection('MyCollection');
$cursor = $collection->find(array(), array("name"=>1, "components"=>1));
foreach($cursor as $key){
echo($key['name'].' components: '.count($key['components']);
}
Ran across this today, If your using the new driver with aggregate you can do this in php, ( given this schema )
{name: 'Some Name', components: {ARRAY OF ITEMS}}
In PHP:
$collection = (new Client())->db->my_collection;
$collection->aggregate([
'$match' => ['name' => 'Some Name'],
'$group' => [
'_id' => null,
'total'=> ['$sum' => "\$components"]
]
]);
The trick here with PHP is to escape the $ dollar sign, this is basically what the mongo documentation says when using size or sum
https://docs.mongodb.com/manual/reference/operator/aggregation/size/
https://docs.mongodb.com/manual/reference/operator/aggregation/sum/
The problem I had is mongo puts fields in as "$field" and PHP doesn't like that at all because of the way it does variable interpolation. However, once you escape the $, it works fine.
I think for this particular case you'd need to do something similar but with $project instead of $group Like this
$collection = (new Client())->db->my_collection;
$collection->aggregate([
'$match' => ['name' => 'Some Name'],
'$project' => [
'name' => "\$name",
'total'=> ['$sum' => "\$components"]
]
]);
This is an old question but seeing as there is no answer picked, I'll just leave this here.

How to get affected number of rows using mongodb ,php driver

I have two problem : How can I get affected rows by php mongodb driver ,and how about the last insert id ? thanks .
You can get number of results right from the cursor using count function:
$collection->find()->count();
You can even get number of all records in collection using:
$collection->count();
Using insert method, _id is added to input array automatically.
$a = array('x' => 1);
$collection->insert($a,array('safe'=>true));
var_dump($a);
array(2) {
["x"]=>
int(1)
["_id"]=>
object(MongoId)#4 (0) {
}
}
I don't believe that there is any type of affected_rows() method at your disposal with mongodb. As for the last insert _id You can generate them in your application code and include them in your insert, so there's really no need for any mysql like insert_id() method.
$id = new MongoId();
$collection->insert(array('
'_id' => $id,
'username' => 'username',
'email' => 'johndoe#gmail.com'
'));
Now you can use the object stored in $id however you wish.
Maybe MongoDB::lastError is what you are looking for:
(http://php.net/manual/en/mongodb.lasterror.php)
It calls the getLastError command:
(http://www.mongodb.org/display/DOCS/getLastError+Command)
which returns, among other things:
n - if an update was done, this is the number of documents updated.
For number of affected rows:
$status = $collection->update( $criteria, array( '$set' => $data ) );
$status['n']; // 'n' is the number of affected rows
If you have the output of your action, you can call relative function:
// $m hold mongo library object
$output = $m->myCollection->updateOne([
'_id' => myMongoCreateID('56ce2e90c9c037dba19c3ce1')], [
'$set' => ['column' => 'value']
]);
// get number of modified records
$count = $output->getModifiedCount();
$output is of of type MongoDB\UpdateResult. Relatively check following files to figure out the best function to find inserted, deleted, matched or whatever result you need:
https://github.com/mongodb/mongo-php-library/blob/master/src/InsertManyResult.php
https://github.com/mongodb/mongo-php-library/blob/master/src/DeleteResult.php
https://github.com/mongodb/mongo-php-library/blob/master/src/InsertOneResult.php
https://github.com/mongodb/mongo-php-library/blob/master/src/UpdateResult.php