Package org.apache.stanbol.entityhub.servicesapi.query

Examples of org.apache.stanbol.entityhub.servicesapi.query.FieldQuery


     * @param patternType
     */
    private String generateSparqlQueryString(String textWithDoubleQuote, PatternType patternType) {
      int limit = 10;
      FieldQueryFactory qf = DefaultQueryFactory.getInstance();
      FieldQuery query = qf.createFieldQuery();
     
      String DEFAULT_AUTOCOMPLETE_SEARCH_FIELD = NamespaceEnum.rdfs+"label";
     
      Collection<String> selectedFields = new ArrayList<String>();
      selectedFields.add(DEFAULT_AUTOCOMPLETE_SEARCH_FIELD);
      query.addSelectedFields(selectedFields);
      query.setConstraint(DEFAULT_AUTOCOMPLETE_SEARCH_FIELD,
          new TextConstraint(textWithDoubleQuote, patternType, true, "en",null));
      query.setLimit(10);
      query.setOffset(0);
     
      final SparqlFieldQuery sparqlQuery = SparqlFieldQueryFactory.getSparqlFieldQuery(query);
     
      return SparqlQueryUtils.createSparqlSelectQuery(sparqlQuery, false,limit,SparqlEndpointTypeEnum.Standard);
  }
View Full Code Here


                                .entity(messsage)
                                .header(HttpHeaders.ACCEPT, acceptedMediaType).build();
                    }
                }
            }
            FieldQuery query = JerseyUtils.createFieldQueryForFindRequest(name, property, language,
                limit == null || limit < 1 ? DEFAULT_FIND_RESULT_LIMIT : limit, offset,ldpath);
           
            // For the Entityhub we support to select additional fields for results
            // of find requests. For the Sites and {site} endpoint this is currently
            // deactivated because of very bad performance with OPTIONAL graph patterns
            // in SPARQL queries.
            Collection<String> additionalSelectedFields = new ArrayList<String>();
            if (select != null && !select.isEmpty()) {
                for (String selected : select.trim().split(" ")) {
                    if (selected != null && !selected.isEmpty()) {
                        additionalSelectedFields.add(selected);
                    }
                }
            }
            query.addSelectedFields(additionalSelectedFields);
            return executeQuery(query, headers, acceptedMediaType);
        }
    }
View Full Code Here

        test1.add(field, "This is the text content of a field with value1.");
        test2.add(field, "This is the text content of a field with value2.");
        Iterable<Representation> updatedIterable = yard.update(Arrays.asList(test1, test2));
        assertNotNull(updatedIterable);

        FieldQuery query = yard.getQueryFactory().createFieldQuery();
        query.setConstraint(field, new TextConstraint(Arrays.asList("text content")));
        QueryResultList<Representation> results = yard.find(query);
        assertEquals(2, results.size());

        // fetch the light / minimal representation
        query = yard.getQueryFactory().createFieldQuery();
        query.setConstraint(field, new TextConstraint(Arrays.asList("value2")));
        results = yard.find(query);
        assertEquals(1, results.size());
        Representation result = results.iterator().next();
        assertEquals("urn:yard.test.testFieldQuery:representation.id2", result.getId());
        assertEquals(null, result.getFirst(field));
View Full Code Here

        Iterable<Representation> updatedIterable = yard.update(Arrays.asList(test1, test2, test3));
        assertNotNull(updatedIterable);

        // Perform a first similarity query that looks a lot like the first document
        FieldQuery query = yard.getQueryFactory().createFieldQuery();
        query.setConstraint(similarityfield, new SimilarityConstraint("aaaa aaaa aaaa aaaa zzzz yyyy"));
        QueryResultList<Representation> results = yard.find(query);
        assertEquals(2, results.size());
        Iterator<Representation> it = results.iterator();
        Representation first = it.next();
        assertEquals("urn:yard.test.testFieldQueryWithSimilarityConstraint:representation.id1", first.getId());
        // assertEquals(0.99, first.getFirst("http://www.iks-project.eu/ontology/rick/query/score"));

        Representation second = it.next();
        assertEquals("urn:yard.test.testFieldQueryWithSimilarityConstraint:representation.id2",
            second.getId());
        // assertEquals(0.80, first.getFirst("http://www.iks-project.eu/ontology/rick/query/score"));

        // combine similarity with traditional filtering
        query = yard.getQueryFactory().createFieldQuery();
        query.setConstraint(similarityfield, new SimilarityConstraint("aaaa aaaa aaaa aaaa zzzz yyyy"));
        query.setConstraint(filterfield, new TextConstraint(Arrays.asList("other")));
        results = yard.find(query);
        assertEquals(1, results.size());
        it = results.iterator();
        first = it.next();
        assertEquals("urn:yard.test.testFieldQueryWithSimilarityConstraint:representation.id2", first.getId());
View Full Code Here

    }

    private QueryResultList<Representation> find(final FieldQuery parsedQuery, SELECT select) throws YardException {
        //create a clone of the query, because we need to refine it because the
        //query (as executed) needs to be included in the result set
        FieldQuery fieldQuery = parsedQuery.clone();
        log.debug("find " + fieldQuery);
        long start = System.currentTimeMillis();
        final Set<String> selected;
        if (select == SELECT.QUERY) {
            // if query set the fields to add to the result Representations
            selected = new HashSet<String>(fieldQuery.getSelectedFields());
            // add the score to query results!
            selected.add(RdfResourceEnum.resultScore.getUri());
        } else {
            // otherwise add all fields
            selected = null;
View Full Code Here

    @Override
    public final QueryResultList<String> findReferences(FieldQuery parsedQuery) throws YardException {
        //create a clone of the query, because we need to refine it because the
        //query (as executed) needs to be included in the result set
        FieldQuery fieldQuery = parsedQuery.clone();
        final SolrQuery query = solrQueryFactoy.parseFieldQuery(fieldQuery, SELECT.ID);
        if(closed){
            log.warn("The SolrYard '{}' was already closed!",config.getName());
        }
        QueryResponse response;
View Full Code Here

                                      NamespacePrefixService nsPrefixService) throws JSONException,WebApplicationException {
        if(jsonQueryString == null){
            throw new IllegalArgumentException("The parsed JSON object MUST NOT be NULL!");
        }
        JSONObject jQuery = new JSONObject(jsonQueryString);
        FieldQuery query;
        if(jQuery.has("ldpath")){ //STANBOL-417: support for using LDPath as select
            LDPathFieldQueryImpl ldPathQuery = new LDPathFieldQueryImpl();
            ldPathQuery.setLDPathSelect(jQuery.getString("ldpath"));
            query = ldPathQuery;
        } else {
            query = new FieldQueryImpl();
        }
        if(!jQuery.has("constraints")){
            StringBuilder message = new StringBuilder();
            message.append("The parsed Field Query MUST contain at least a single 'constraints'\n");
            message.append("Parsed Query:\n");
            message.append(jQuery.toString(4));
            log.warn(message.toString());
            throw new WebApplicationException(
                Response.status(Status.BAD_REQUEST).entity(
                    message.toString()).header(HttpHeaders.ACCEPT, acceptedMediaType.toString())
                    .build());
        }
        JSONArray constraints = jQuery.getJSONArray("constraints");
        //collect all parsing Errors to report a complete set of all errors
        boolean parsingError = false;
        StringBuilder parsingErrorMessages = new StringBuilder();
        parsingErrorMessages.append("Constraint parsing Errors:\n");
        for(int i=0;i<constraints.length();i++){
            JSONObject jConstraint = constraints.getJSONObject(i);
            if(jConstraint.has("field")){
                String field = jConstraint.getString("field");
                //check if there is already a constraint for that field
                if(field == null || field.isEmpty()){
                    parsingErrorMessages.append('\n');
                    parsingErrorMessages.append(
                        "Each Field Query Constraint MUST define a value for 'field'\n");
                    parsingErrorMessages.append("Parsed Constraint:\n");
                    parsingErrorMessages.append(jConstraint.toString(4));
                    parsingErrorMessages.append('\n');
                    parsingError = true;
                    continue;
                }
                String fieldUri = nsPrefixService.getFullName(field);
                if(fieldUri == null){
                    parsingErrorMessages.append('\n');
                    parsingErrorMessages.append(
                        "The 'field' '").append(field).append("uses an unknown namespace prefix '");
                    parsingErrorMessages.append(NamespaceMappingUtils.getPrefix(field)).append("'\n");
                    parsingErrorMessages.append("Parsed Constraint:\n");
                    parsingErrorMessages.append(jConstraint.toString(4));
                    parsingErrorMessages.append('\n');
                    parsingError = true;
                    continue;
                }else if(query.isConstrained(fieldUri)){
                    parsingErrorMessages.append('\n');
                    parsingErrorMessages.append(
                        "The parsed Query defines multiple constraints fr the field '"
                        +fieldUri+"'!\n");
                    parsingErrorMessages.append("FieldQuery allows only a single Constraint for a field\n");
                    parsingErrorMessages.append("Parsed Constraints:\n");
                    parsingErrorMessages.append(constraints.toString(4));
                    parsingErrorMessages.append('\n');
                    parsingError = true;
                    continue;
                } else {
                    try {
                        query.setConstraint(fieldUri, parseConstraint(jConstraint,nsPrefixService));
                    } catch (IllegalArgumentException e) {
                        parsingErrorMessages.append('\n');
                        parsingErrorMessages.append(e.getMessage());
                        parsingErrorMessages.append('\n');
                        parsingError = true;
                        continue;
                    }
                }
            } else { //empty field
                parsingErrorMessages.append('\n');
                parsingErrorMessages.append("Constraints MUST define a value for 'field'\n");
                parsingErrorMessages.append("Parsed Constraint:\n");
                parsingErrorMessages.append(jConstraint.toString(4));
                parsingErrorMessages.append('\n');
                parsingError = true;
                continue;
            }
        }
        if(parsingError){
            String message = parsingErrorMessages.toString();
            log.warn(message);
            throw new WebApplicationException(
                Response.status(Status.BAD_REQUEST).entity(
                    message).header(HttpHeaders.ACCEPT, acceptedMediaType.toString())
                    .build());
        }
        //parse selected fields
        JSONArray selected = jQuery.optJSONArray("selected");
        if(selected != null){
            for(int i=0;i<selected.length();i++){
                String selectedField = selected.getString(i);
                selectedField = nsPrefixService.getFullName(selectedField);
                if(selectedField != null && !selectedField.isEmpty()){
                    query.addSelectedField(selectedField);
                }
            }
        } //else no selected fields -> funny but maybe someone do need only the ids
        //parse limit and offset
        if(jQuery.has("limit") && !jQuery.isNull("limit")){
            try {
                query.setLimit(jQuery.getInt("limit"));
            } catch (JSONException e) {
                parsingErrorMessages.append('\n');
                parsingErrorMessages.append("Property \"limit\" MUST BE a valid integer number!\n");
                parsingErrorMessages.append("Parsed Value:");
                parsingErrorMessages.append(jQuery.get("init"));
                parsingErrorMessages.append('\n');
                parsingError = true;
            }
        }
        if(jQuery.has("offset") && !jQuery.isNull("offset")){
            try {
                query.setOffset(jQuery.getInt("offset"));
            } catch (JSONException e) {
                parsingErrorMessages.append('\n');
                parsingErrorMessages.append("Property \"offset\" MUST BE a valid integer number!\n");
                parsingErrorMessages.append("Parsed Value:");
                parsingErrorMessages.append(jQuery.get("init"));
View Full Code Here

        // the Entityhub
        FieldQueryFactory queryFactory = site == null ? entityhub.getQueryFactory() : site.getQueryFactory();

        log.trace("Will use a query-factory of type [{}].", queryFactory.getClass().toString());

        FieldQuery query = queryFactory.createFieldQuery();

        // replace spaces with plus to create an AND search for all words in the
        // name!
        Constraint labelConstraint;
        // TODO: make case sensitivity configurable
        boolean casesensitive = false;
        String namedEntityLabel = casesensitive ? namedEntity.getName() : namedEntity.getName().toLowerCase();
        if (language != null) {
            // search labels in the language and without language
            labelConstraint = new TextConstraint(namedEntityLabel, casesensitive, language, null);
        } else {
            labelConstraint = new TextConstraint(namedEntityLabel, casesensitive);
        }
        query.setConstraint(nameField, labelConstraint);
        if (OntologicalClasses.DBPEDIA_PERSON.equals(namedEntity.getType())) {
            if (personState) {
                if (personType != null) {
                    query.setConstraint(RDF_TYPE.getUnicodeString(), new ReferenceConstraint(personType));
                }
                // else no type constraint
            } else {
                // ignore people
                return Collections.emptyList();
            }
        } else if (DBPEDIA_ORGANISATION.equals(namedEntity.getType())) {
            if (orgState) {
                if (orgType != null) {
                    query.setConstraint(RDF_TYPE.getUnicodeString(), new ReferenceConstraint(orgType));
                }
                // else no type constraint
            } else {
                // ignore people
                return Collections.emptyList();
            }
        } else if (OntologicalClasses.DBPEDIA_PLACE.equals(namedEntity.getType())) {
            if (this.placeState) {
                if (this.placeType != null) {
                    query.setConstraint(RDF_TYPE.getUnicodeString(), new ReferenceConstraint(placeType));
                }
                // else no type constraint
            } else {
                // ignore people
                return Collections.emptyList();
            }
        }
        query.setLimit(Math.max(20, this.numSuggestions * 3));

        log.trace("A query has been created of type [{}] and the following settings:\n{}", query.getClass()
                .toString(), query.toString());

        if (null == site) log.trace("A query will be sent to the entity-hub of type [{}].", entityhub
                .getClass());
        else log.trace("A query will be sent to a site [id :: {}][type :: {}].", site.getId(), site
                .getClass());
View Full Code Here

        //TODO: The QueryResultList expects that the query as executed is added
        //to the response. However when executing queries on multiple site they
        //might support a different set of features and therefore execute
        //different variants. For now I return simple the query as executed by
        //the first Site that contributes results
        FieldQuery processedQuery = null;
        FieldQuery queryWithResults = null;
        for(Site site : referencedSites){
            if(site.supportsSearch()){
                log.debug(" > query site {}",site.getId());
                try {
                    QueryResultList<String> results = site.findReferences(query);
View Full Code Here

        //TODO: The QueryResultList expects that the query as executed is added
        //to the response. However when executing queries on multiple site they
        //might support a different set of features and therefore execute
        //different variants. For now I return simple the query as executed by
        //the first Site that contributes results
        FieldQuery processedQuery = null;
        FieldQuery queryWithResults = null;
        for(Site site : referencedSites){
            if(site.supportsSearch()){
                log.debug(" > query site {}",site.getId());
                try {
                    QueryResultList<Representation> results = site.find(query);
View Full Code Here

TOP

Related Classes of org.apache.stanbol.entityhub.servicesapi.query.FieldQuery

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.