-
Notifications
You must be signed in to change notification settings - Fork 0
/
Python_Solr
76 lines (57 loc) · 2.42 KB
/
Python_Solr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
pysolr is a lightweight Python wrapper for Apache Solr. It provides an interface that queries the server and returns results based on the query.
Reference - https://pypi.org/project/pysolr/
Installation - pip install pysolr
Or if you want to install directly from the repository: python setup.py install, or drop the pysolr.py file anywhere on your PYTHONPATH
--------------------------------------------------------------sample code------------------------------------------------------
# If on Python 2.X
from __future__ import print_function
import pysolr
# Setup a Solr instance. The timeout is optional.
solr = pysolr.Solr('http://localhost:8983/solr/', timeout=10, auth=<type of authentication>)
# How you'd index data.
solr.add([
{
"id": "doc_1",
"title": "A test document",
},
{
"id": "doc_2",
"title": "The Banana: Tasty or Dangerous?",
"_doc": [
{ "id": "child_doc_1", "title": "peel" },
{ "id": "child_doc_2", "title": "seed" },
]
},
])
# Note that the add method has commit=True by default, so this is
# immediately committed to your index.
# You can index a parent/child document relationship by
# associating a list of child documents with the special key '_doc'. This
# is helpful for queries that join together conditions on children and parent
# documents.
# Later, searching is easy. In the simple case, just a plain Lucene-style
# query is fine.
results = solr.search('bananas')
# The ``Results`` object stores total results found, by default the top
# ten most relevant results and any additional data like
# facets/highlighting/spelling/etc.
print("Saw {0} result(s).".format(len(results)))
# Just loop over it to access the results.
for result in results:
print("The title is '{0}'.".format(result['title']))
# For a more advanced query, say involving highlighting, you can pass
# additional options to Solr.
results = solr.search('bananas', **{
'hl': 'true',
'hl.fragsize': 10,
})
# You can also perform More Like This searches, if your Solr is configured
# correctly.
similar = solr.more_like_this(q='id:doc_2', mltfl='text')
# Finally, you can delete either individual documents,
solr.delete(id='doc_1')
# also in batches...
solr.delete(id=['doc_1', 'doc_2'])
# ...or all documents.
solr.delete(q='*:*')
---------------------------------------------------- end of sample code ----------------------------------------------------