使用 Python/Jython 的 JDBC
Solr 的 JDBC 驱动程序支持 Python 和 Jython。
Python
Python 支持使用 JayDeBeApi 库访问 JDBC。必须配置 CLASSPATH 变量以包含 solr-solrj
jar 和支持的 solrj-lib
jar。
JayDeBeApi
run.sh
#!/usr/bin/env bash
# Java must already be installed
pip install JayDeBeApi
export CLASSPATH="/opt/solr/server/lib/ext/*:/opt/solr/server/solr-webapp/webapp/WEB-INF/lib/*"
python solr_jaydebeapi.py
solr_jaydebeapi.py
#!/usr/bin/env python
# https://pypi.python.org/pypi/JayDeBeApi/
import jaydebeapi
import sys
if __name__ == '__main__':
jdbc_url = "jdbc:solr://localhost:9983?collection=test"
driverName = "org.apache.solr.client.solrj.io.sql.DriverImpl"
statement = "select fielda, fieldb, fieldc, fieldd_s, fielde_i from test limit 10"
conn = jaydebeapi.connect(driverName, jdbc_url)
curs = conn.cursor()
curs.execute(statement)
print(curs.fetchall())
conn.close()
sys.exit(0)
Jython
Jython 支持使用 Java 接口或 zxJDBC 库以原生方式访问 JDBC。必须配置 CLASSPATH 变量以包含 solr-solrj jar 和支持的 solrj-lib jar。
run.sh
#!/usr/bin/env bash
# Java and Jython must already be installed
export CLASSPATH="/opt/solr/server/lib/ext/*:/opt/solr/server/solr-webapp/webapp/WEB-INF/lib/*"
jython [solr_java_native.py | solr_zxjdbc.py]
Java 原生
solr_java_native.py
#!/usr/bin/env jython
# https://docs.jython.cn/en/latest/DatabasesAndJython/
# https://wiki.python.org/jython/DatabaseExamples#SQLite_using_JDBC
import sys
from java.lang import Class
from java.sql import DriverManager, SQLException
if __name__ == '__main__':
jdbc_url = "jdbc:solr://localhost:9983?collection=test"
driverName = "org.apache.solr.client.solrj.io.sql.DriverImpl"
statement = "select fielda, fieldb, fieldc, fieldd_s, fielde_i from test limit 10"
dbConn = DriverManager.getConnection(jdbc_url)
stmt = dbConn.createStatement()
resultSet = stmt.executeQuery(statement)
while resultSet.next():
print(resultSet.getString("fielda"))
resultSet.close()
stmt.close()
dbConn.close()
sys.exit(0)
zxJDBC
solr_zxjdbc.py
#!/usr/bin/env jython
# https://docs.jython.cn/en/latest/DatabasesAndJython/
# https://wiki.python.org/jython/DatabaseExamples#SQLite_using_ziclix
import sys
from com.ziclix.python.sql import zxJDBC
if __name__ == '__main__':
jdbc_url = "jdbc:solr://localhost:9983?collection=test"
driverName = "org.apache.solr.client.solrj.io.sql.DriverImpl"
statement = "select fielda, fieldb, fieldc, fieldd_s, fielde_i from test limit 10"
with zxJDBC.connect(jdbc_url, None, None, driverName) as conn:
with conn:
with conn.cursor() as c:
c.execute(statement)
print(c.fetchall())
sys.exit(0)