I'm using pysolr to save a list of classes into my local solr database, my problem is that when i encode my list of classes with jsonpickle, the query is rejected with this message, although if i print the json generated by josnpickle i get no problem saving the data into solr.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-2-3b6d9f42d0ec> in <module>()
27 json=str(jsonpickle.encode(coreData, unpicklable=False))
28 print(json)
---> 29 solr.add(json)
C:\ProgramData\Anaconda3\lib\site-packages\pysolr.py in add(self, docs, boost, fieldUpdates, commit, softCommit, commitWithin, waitFlush, waitSearcher, overwrite, handler)
878
879 for doc in docs:
--> 880 el = self._build_doc(doc, boost=boost, fieldUpdates=fieldUpdates)
881 message.append(el)
882
C:\ProgramData\Anaconda3\lib\site-packages\pysolr.py in _build_doc(self, doc, boost, fieldUpdates)
798 doc_elem = ElementTree.Element('doc')
799
--> 800 for key, value in doc.items():
801 if key == NESTED_DOC_KEY:
802 for child in value:
AttributeError: 'str' object has no attribute 'items'
my code:
from solrq import Q
import pysolr
import jsonpickle
from datetime import datetime, timedelta
from Model import Twitter
#conexion a solr
solr = pysolr.Solr('http://localhost:8983/solr/twitter')
#query
query = Q(label="none")
results = solr.search(query)
print("Saw {0} result(s).".format(len(results)))
#testing the query
for result in results:
print("-->".format(result['content']))
#creating a new class with data
twit = Twitter("000002","content text","some label")
#list of twitter classes
coreData=[]
coreData.append(twit)
#encoding to json
json=str(jsonpickle.encode(coreData, unpicklable=False))
print(json)
#saving to solr
solr.add(json)
This is what prints after encoding the list of classes into json [{"content": "content text", "id": "000002", "label": "some label"}]
as i said before if i substitute the json variable with this string the data is saved but i have no idea why, even if cast as a string like this solr.add(str(json))
get the same error message.
The problem here is, that pysolr for method add
Requires
docs
, which is a list of dictionaries. Each key is the field name and each value is the value to index.
You need to create dictionary from your object, not strings. You could do it by calling vars
on an object
coreData=[]
coreData.append(vars(twit))
solr.add(coreData)