How can I index properties in Memgraph? - memgraphdb

How can I index properties in the Node and Relationship classes I created in Memgraph with GQLAlchemy? Is it possible to create only a Label index?

Check out Memgraph's documentation. There are some great and simple examples that explain the process. For example,
from gqlalchemy import Memgraph, Node, Field
db = Memgraph()
class Animal(Node, index=True, db=db):
name: str
class Human(Node):
id: str = Field(index=True, db=db)
In the first class, Animal, the class argument index is set to True. That means that Memgraph will create a label index on the label Animal.
The other class, Human, has a Field() index argument set to True. Hence, Memgraph will create a label-property index on the property id of every node labeled Human.

Related

Django rest framework mongoengine update new field with default value

I'm using Django rest framework mongoengine after created few documents, if i want add a new field with default value. Is there any way to do that orelse i need to update with few custom function.
Note: I want to fetch the data with filter having a new field name. That time the field is not there. So i'm getting empty.
From what I understand, you are modifying a MongoEngine model (adding a field with a default value) after documents were inserted. And you are having issue when filtering your collection on that new field.
Basically you have the following confusing situation:
from mongoengine import *
conn = connect()
conn.test.test_person.insert({'age': 5}) # Simulate an old object
class TestPerson(Document):
name = StringField(default='John') # the new field
age = IntField()
person = TestPerson.objects().first()
assert person.name == "John"
assert Test.objects(name='John').count() == 0
In fact, MongoEngine dynamically applies the default value when the field of the underlying pymongo document is empty but it doesn't account for that when filtering.
The only reliable way to guarantee that filtering will work is to migrate your existing documents.
If its only adding a field with a default value, you could do this with MongoEngine: TestPerson.objects().update(name='John')
If you did more important/complicated changes to your document structure, then the best option is to get down to pymongo.
coll = TestPerson._get_collection()
coll.update({}, {'$set': {'name': 'John'}})

sql_cosntraints on exitsing field from original module

In product.template there is field default_code. Is it' possible to add sql_constraints that default code should be unique. Because this code doesn't work. Or do i need override default_code field in my costume module?
class ProductProduct(models.Model):
_inherit = 'product.template'
_sql_constraints = [
('code_uniq', 'unique (default_code)', "Default code already exists!"),
]
Please try with Python constrain may its useful for you :
import this lines in python file :
from openerp.exceptions import ValidationError
Any write this method in your class :
#api.constrains('default_code')
def _check_default_code(self):
code = self.search([('default_code','=',self.default_code)])
if len(code) > 1:
raise ValidationError(_("Duplicate Record"))
I would add the constraint on model product.product because that's where this information (product reference) really is used. But default_code on product.template will only work since Odoo V10. In Odoo V8 and V9 it was a unstored related field, so not in DB. So you have to add the constraint on model product.product.
class ProductProduct(models.Model):
_inherit = 'product.product'
_sql_constraints = [
('code_uniq', 'unique(default_code)', "Default code already exists!"),
]
Important to know: If the module, which sets up the constraint, is updated while the constraint will fail (e. g. the default_code actually twice in db), it won't create a sql constraint in db. So you have to clean up the data and update the module again or create the constraint in the db by yourself.

Odoo 10 - Duplicate supplier info for a given product_template

I have:
a) given product_template_id (i.e. id 100) and
b) a duplicated product_template_id (i.e. id 200) created using copy() method
copy() method copies only product.template model, so suppliers for that specific product are not copied.
I would like to duplicate all suppliers for that model, but now I am wondering which is the right way to do it in Odoo.
If I understood the model properly suppliers prices for a given product are stored in product_supplierinfo table, where each record that points to a given product_tmpl_id specifices a supplier price/qty for a given product_template.
Which would be the way in Odoo to search for all records that point to a given product_tmpl_id (i.e. 100), duplicate them changing product_tmpl_id to the new one (i.e. 200)?
Excerpt from the ORM Documentation:
copy (bool) -- whether the field value should be copied when the record is duplicated (default: True for normal fields, False for One2many and computed fields, including property fields and related fields)
The field you're referring to is seller_ids, whose field definition is below:
seller_ids = fields.One2many('product.supplierinfo', 'product_tmpl_id', 'Vendors')
The copy attribute is not explicitly defined, so it is False by default (as explained in the documentation above). If you want this field to copy along with the other values during the standard product "Duplicate" (copy method), you can do this:
class ProductTemplate(models.Model):
_inherit = 'product.template'
# This only changes the copy attribute of the existing seller_ids field.
# All other attributes (string, comodel_name, etc.) remain as they are defined in core.
seller_ids = fields.One2many(copy=True)
Alternatively
If you want to only have the field copied sometimes, you can extend the copy method to look for a specific context value and only copy based on that.
# This may take some tweaking, but here's the general idea
#api.multi
def copy(self, vals):
new_product = super(YourClass, self).copy(vals)
if vals.get('copy_sellers'):
new_product.seller_ids = self.seller_ids.copy({'product_id': new_product.id})
return new_product
# Whatever you have calling the copy method will need to include copy_sellers in vals
vals.update({'copy_sellers': True})
product.copy(vals)

How can I add multiple instances to a Django reverse foreign key set in a minimal number of hits to the database?

For example, I have two models:
class Person(models.Model):
name = models.CharField(max_length=100)
class Job(models.Model):
title = models.CharField(max_length=100)
person = models.ForeignKey(Person)
I have a list of job ids--
job_ids = [1, 2, ....]
that are pks of Job model instances
I know I can do--
for id in job_ids:
person.jobs.add(job_id)
but this will be many more queries than if I could do--
person.jobs.add(job_ids)
where it would unpack the list and use bulk_create. How do I do this? Thanks.
Have you tried
person.jobs.add(*job_ids)
In my case I used a filter query and had a list of objects (as opposed to IDs). I was getting an error similar to
TypeError: 'MyModel' instance expected, got [<MyModel: MyModel Object>]
...before I included the asterisk.
credit (another SO question)
If you didn't create your jobs yet, you can create them by adding bulk=False
jobs_list=[
Job(title='job_1'),
Job(title='job_2')
[
person.jobs.add(*jobs_list, bulk=False) # your related_name should be 'jobs', otherwhise use 'job_sets'.

Interacting With Class Objects in Ruby

How can I interact with objects I've created based on their given attributes in Ruby?
To give some context, I'm parsing a text file that might have several hundred entries like the following:
ASIN: B00137RNIQ
-------------------------Status Info-------------------------
Upload created: 2010-04-09 09:33:45
Upload state: Imported
Upload state id: 3
I can parse the above with regular expressions and use the data to create new objects in a "Product" class:
class Product
attr_reader :asin, :creation_date, :upload_state, :upload_state_id
def initialize(asin, creation_date, upload_state, upload_state_id)
#asin = asin
#creation_date = creation_date
#upload_state = upload_state
#upload_state_id = upload_state_id
end
end
After parsing, the raw text from above will be stored in an object that look like this:
[#<Product:0x00000101006ef8 #asin="B00137RNIQ", #creation_date="2010-04-09 09:33:45 ", #upload_state="Imported ", #upload_state_id="3">]
How can I then interact with the newly created class objects? For example, how might I pull all the creation dates for objects with an upload_state_id of 3? I get the feeling I'm going to have to write class methods, but I'm a bit stuck on where to start.
You would need to store the Product objects in a collection. I'll use an array
product_collection = []
# keep adding parse products into the collection as many as they are
product_collection << parsed_product_obj
#next select the subset where upload_state_ud = 3
state_3_products = product_collection.select{|product| product.upload_state_id == 3}
attr reader is a declarative way of defining properties/attributes on your product class. So you can access each value as obj.attribute like I have done for upload_state_id above.
select selects the elements in the target collection, which meet a specific criteria. Each element is assigned to product, and if the criteria evaluates to true is placed in the output collection.

Resources