org.apache.jena.query.Query类的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(11.2k)|赞(0)|评价(0)|浏览(246)

本文整理了Java中org.apache.jena.query.Query类的一些代码示例,展示了Query类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Query类的具体详情如下:
包路径:org.apache.jena.query.Query
类名称:Query

Query介绍

[英]The data structure for a query as presented externally. There are two ways of creating a query - use the parser to turn a string description of the query into the executable form, and the programmatic way (the parser is calling the programmatic operations driven by the query string). The declarative approach of passing in a string is preferred. Once a query is built, it can be passed to the QueryFactory to produce a query execution engine.
[中]外部显示的查询的数据结构。创建查询有两种方法——使用解析器将查询的字符串描述转换为可执行形式,以及编程方式(解析器调用由查询字符串驱动的编程操作)。最好使用传递字符串的声明性方法。一旦构建了查询,就可以将其传递给QueryFactory以生成查询执行引擎。

代码示例

代码示例来源:origin: apache/jena

static private String labelForQuery(Query q) {
  if ( q.isSelectType() )     return "SELECT" ; 
  if ( q.isConstructType() )  return "CONSTRUCT" ; 
  if ( q.isDescribeType() )   return "DESCRIBE" ; 
  if ( q.isAskType() )        return "ASK" ;
  if ( q.isJsonType() )       return "JSON" ;
  return "<<unknown>>" ;
}

代码示例来源:origin: apache/tinkerpop

final List<String> vars = query.getResultVars();
if (!query.isQueryResultStar() && !query.hasGroupBy()) {
  final String[] all = new String[vars.size()];
  vars.toArray(all);
  if (query.isDistinct()) {
    traversal = traversal.dedup(all);
if (query.hasGroupBy()) {
  final VarExprList lstExpr = query.getGroupBy();
  String grpVar = "";
  for (Var expr : lstExpr.getVars()) {
    grpVar = expr.getName();
  if (query.hasAggregators()) {
    final List<ExprAggregator> exprAgg = query.getAggregators();
    for (ExprAggregator expr : exprAgg) {
      if (expr.getAggregator().getName().contains("COUNT")) {
        if (!query.toString().contains("GROUP")) {
          if (expr.getAggregator().toString().contains("DISTINCT"))
            traversal = traversal.dedup(expr.getAggregator().getExprList().get(0).toString().substring(1));
if (query.hasOrderBy() && query.hasGroupBy())
  orderingIndex.forEach((k, v) -> traversal = traversal.order().by(__.select(k), v));
if (query.hasLimit()) {
  long limit = query.getLimit(), offset = 0;
  if (query.hasOffset())
    offset = query.getOffset();

代码示例来源:origin: SmartDataAnalytics/jena-sparql-api

@Deprecated // Remove once countQuery works as espected
public static long countQueryOld(Query query, QueryExecutionFactory qef) {
  Var outputVar = Var.alloc("_c_");
  if(query.isConstructType()) {
    Element element = query.getQueryPattern();
    query = new Query();
    query.setQuerySelectType();
    query.setQueryResultStar(true);
    query.setQueryPattern(element);
  }
  Query countQuery = QueryFactory.create("Select (Count(*) As ?_c_) { {" + query + "} }", Syntax.syntaxSPARQL_11);
  QueryExecution qe = qef.createQueryExecution(countQuery);
  ResultSet rs = qe.execSelect();
  Binding binding = rs.nextBinding();
  Node node = binding.get(outputVar);
  Number numeric = (Number)node.getLiteralValue();
  long result = numeric.longValue();
  return result;
}

代码示例来源:origin: apache/jena

protected Query elementToQuery(Element pattern) {
  if ( pattern == null )
    return null;
  Query query = new Query();
  query.setQueryPattern(pattern);
  query.setQuerySelectType();
  query.setQueryResultStar(true);
  query.setResultVars();
  return query;
}

代码示例来源:origin: SmartDataAnalytics/jena-sparql-api

public static long adjustPageSize(QueryExecutionFactory factory, long requestedPageSize) {
    Query query = CannedQueryUtils.spoTemplate();
    query.setLimit(requestedPageSize);

    //System.out.println(query);
    QueryExecution qe = factory.createQueryExecution(query);
    ResultSet rs = qe.execSelect();

    long size = 0;
    while(rs.hasNext()) {
      ++size;
      rs.next();
    }
    size = Math.max(size, 1);
    qe.close();

    return size >= requestedPageSize
      ? requestedPageSize
      : size;
  }
}

代码示例来源:origin: org.apache.taverna.language/taverna-robundle

private static List<RDFNode> creatingAgentsFor(Resource r) {
  logger.fine("Finding creator of " + r);
  String queryStr = sparqlPrefixes + "SELECT ?agent WHERE { \n" + " { \n"
      + "  ?r dct:creator [ \n" + "	    rdfs:member ?agent \n"
      + "  ] \n" + " } UNION { \n" + "   ?r dct:creator ?agent .\n "
      + "   FILTER NOT EXISTS { ?agent rdfs:member ?member } \n"
      + " } \n" + "} \n";
  logger.finer(QueryFactory.create(queryStr).toString());
  QueryExecution qexec = QueryExecutionFactory.create(queryStr,
      r.getModel());
  QuerySolutionMap binding = new QuerySolutionMap();
  binding.add("r", r);
  qexec.setInitialBinding(binding);
  ResultSet select = qexec.execSelect();
  List<RDFNode> agents = new ArrayList<>();
  while (select.hasNext()) {
    RDFNode agent = select.next().get("agent");
    logger.fine("Found: " + agent);
    agents.add(agent);
  }
  return agents;
}

代码示例来源:origin: SmartDataAnalytics/jena-sparql-api

public static Query spoCountTemplate(Node s, Node p, Node o)
{
  Query query = QueryFactory.create();
  query.setQuerySelectType();
  Triple triple = new Triple(s, p, o);
  ElementGroup group = new ElementGroup();
  group.addTriplePattern(triple);
  query.setQueryPattern(group);
  if(s.isVariable()) {
    query.getProject().add(Var.alloc(s.getName()));
  }
  if(p.isVariable()) {
    query.getProject().add(Var.alloc(p.getName()));
  }
  if(o.isVariable()) {
    query.getProject().add(Var.alloc(o.getName()));
  }
  
  query.allocAggregate(new AggCount());
  
  return query;
}

代码示例来源:origin: apache/jena

/**
 * Execute a SELECT query and process the rows of the results with the handler code.  
 * @param query
 * @param rowAction
 */
@Override
public default void querySelect(Query query, Consumer<QuerySolution> rowAction) {
  if ( ! query.isSelectType() )
    throw new JenaConnectionException("Query is not a SELECT query");
  Txn.executeRead(this, ()->{ 
    try ( QueryExecution qExec = query(query) ) {
      qExec.execSelect().forEachRemaining(rowAction);
    }
  } ); 
}

代码示例来源:origin: org.aksw.jena-sparql-api/jena-sparql-api-cache

public static Query createQueryCount(Var countVar, Element e, Long limit) {
  if(limit != null) {
    e = limitElement(e, limit);
  }
  Var tmpVar = Var.alloc(countVar.getName() + "_tmp_");
  Query result = new Query();
  result.setQuerySelectType();
  result.getProject().add(countVar, new ExprAggregator(tmpVar, new AggCount()));
  result.setQueryPattern(e);
  return result;
}

代码示例来源:origin: org.aksw.jena-sparql-api/jena-sparql-api-cache

public QueryRunner trySelect(String queryString) {
    Stopwatch sw = Stopwatch.createStarted();

    Query query = new Query();
    query.setPrefixMapping(prefixMapping);

    QueryFactory.parse(query, queryString, "http://example.org/", syntax);

    QueryExecution qe = sparqlService.createQueryExecution(query);
    ResultSet rs = qe.execSelect();
    ResultSetFormatter.consume(rs);

    System.out.println("Time taken: " + sw.elapsed(TimeUnit.MILLISECONDS));

    return this;
  }
}

代码示例来源:origin: apache/jena

private static void test3(String pattern, String... joinForm)
{
  Query q = QueryFactory.create("PREFIX : <http://example/> SELECT * "+pattern) ;
  Op op = Algebra.compile(q.getQueryPattern()) ;
  test(op, joinForm) ;
}

代码示例来源:origin: apache/jena

private QueryExecution queryExec(Query query, String queryString) {
  checkQuery();
  if ( query == null && queryString == null )
    throw new InternalErrorException("Both query and query string are null"); 
  if ( query == null ) {
    if ( parseCheckQueries )
      QueryFactory.create(queryString);
  }

  // Use the query string as provided if possible, otherwise serialize the query.
  String queryStringToSend = ( queryString != null ) ?  queryString : query.toString();
  return exec(()-> createQueryExecution(query, queryStringToSend));
}

代码示例来源:origin: tarql/tarql

private void processResults(TarqlQueryExecution ex) throws IOException {
  if (testQuery && ex.getFirstQuery().getConstructTemplate() != null) {
    IndentedWriter out = new IndentedWriter(System.out); 
    new FmtTemplate(out, new SerializationContext(ex.getFirstQuery())).format(ex.getFirstQuery().getConstructTemplate());
    out.flush();
  }
  if (ex.getFirstQuery().isSelectType()) {
    System.out.println(ResultSetFormatter.asText(ex.execSelect()));
  } else if (ex.getFirstQuery().isAskType()) {
    System.out.println(ResultSetFormatter.asText(ex.execSelect()));
  } else if (ex.getFirstQuery().isConstructType()) {
    resultTripleIterator = resultTripleIterator.andThen(ex.execTriples());
  } else {
    cmdError("Only query forms CONSTRUCT, SELECT and ASK are supported");
  }
}

代码示例来源:origin: apache/jena

/** Return a closable resultset for a {@link QueryExecution}.
 * The {@link QueryExecution} must be for a {@code SELECT} query.
 * @param queryExecution {@code QueryExecution} must be for a {@code SELECT} query.
 * @return ResultSetCloseable
 */
public static ResultSetCloseable closeableResultSet(QueryExecution queryExecution) {
  if ( queryExecution.getQuery() != null && ! queryExecution.getQuery().isSelectType() )
    throw new IllegalArgumentException("Not an execution for a SELECT query");
  return new ResultSetCloseable(queryExecution.execSelect(), queryExecution) ;
}

代码示例来源:origin: apache/jena

public static void executeQuery(Prologue prologue, QueryExecution queryExecution, ResultsFormat outputFormat) {
  Query query = queryExecution.getQuery() ;
  if ( prologue == null )
    prologue = query.getPrologue() ;
  if ( prologue == null )
    prologue = dftPrologue ;
  if ( query.isSelectType() )
    doSelectQuery(prologue, queryExecution, outputFormat) ;
  else if ( query.isDescribeType() )
    doDescribeQuery(prologue, queryExecution, outputFormat) ;
  else if ( query.isConstructQuad() )
    // Before isConstructType.
    doConstructQuadsQuery(prologue, queryExecution, outputFormat) ;
  else if ( query.isConstructType() )
    doConstructQuery(prologue, queryExecution, outputFormat) ;
  else if ( query.isAskType() )
    doAskQuery(prologue, queryExecution, outputFormat) ;
  else if ( query.isJsonType() )
    doJsonQuery(prologue, queryExecution, outputFormat) ;
  else
    throw new QueryException("Unrecognized query form");
}

代码示例来源:origin: apache/jena

/**
 * Makes a copy of this query.  Copies by parsing a query from the serialized form of this query
 * @return Copy of this query
 */
public Query cloneQuery() {
  // A little crude.
  // Must use toString() rather than serialize() because we may not know how to serialize extended syntaxes
  String qs = this.toString();
  return QueryFactory.create(qs, getSyntax()) ;
}

代码示例来源:origin: apache/jena

/**
 * Execute a SELECT query and process the ResultSet with the handler code.  
 * @param query
 * @param resultSetAction
 */
@Override
public default void queryResultSet(Query query, Consumer<ResultSet> resultSetAction) {
  if ( ! query.isSelectType() )
    throw new JenaConnectionException("Query is not a SELECT query");
  Txn.executeRead(this, ()->{ 
    try ( QueryExecution qExec = query(query) ) {
      ResultSet rs = qExec.execSelect();
      resultSetAction.accept(rs);
    }
  } ); 
}

代码示例来源:origin: org.aksw.jena-sparql-api/jena-sparql-api-cache

public static Element limitElement(Element e, long limit) {
  Query subQuery = new Query();
  subQuery.setQuerySelectType();
  subQuery.setQueryResultStar(true);
  subQuery.setQueryPattern(e);
  subQuery.setLimit(limit);
  Element result = new ElementSubQuery(subQuery);
  return result;
}

代码示例来源:origin: SmartDataAnalytics/jena-sparql-api

public static Node extractDescribeNode(Query query) {
  if (!query.isDescribeType()) {
    throw new RuntimeException("DESCRIBE query expected. Got: ["
        + query.toString() + "]");
  }
  // TODO Right now we only support describe with a single constant.
  //Element queryPattern = query.getQueryPattern();
  if(query.getQueryPattern() != null || !query.getResultVars().isEmpty() || query.getResultURIs().size() > 1) {
    throw new RuntimeException("Sorry, DESCRIBE is only implemented for a single resource argument");
  }
  Node result = query.getResultURIs().get(0);
  return result;
}

代码示例来源:origin: apache/jena

/**
 * Execute a query, expecting the result to be one row, one column. Return
 * that one RDFNode
 */
public static RDFNode getExactlyOne(String qs, Dataset ds) {
  Query q = QueryFactory.create(qs) ;
  if ( q.getResultVars().size() != 1 )
    throw new ARQException("getExactlyOne: Must have exactly one result columns") ;
  String varname = q.getResultVars().get(0) ;
  try ( QueryExecution qExec = QueryExecutionFactory.create(q, ds) ) {
    return getExactlyOne(qExec, varname) ;
  }
}

相关文章