Search in sources :

Example 6 with UserFunction

use of org.neo4j.procedure.UserFunction in project neo4j-apoc-procedures by neo4j-contrib.

the class Strings method toCypher.

@UserFunction
@Description("apoc.text.toCypher(value, {skipKeys,keepKeys,skipValues,keepValues,skipNull,node,relationship,start,end}) | tries it's best to convert the value to a cypher-property-string")
public String toCypher(@Name("value") Object value, @Name(value = "config", defaultValue = "{}") Map<String, Object> config) {
    if (config.containsKey("keepValues") && !((Collection) config.get("keepValues")).stream().noneMatch((v) -> (v.getClass().isInstance(value) || isPrimitive(value) && isPrimitive(v)) && !value.equals(v)))
        return null;
    else if (config.containsKey("skipValues") && ((Collection) config.get("skipValues")).contains(value))
        return null;
    if (value == null)
        return "null";
    if (value instanceof Number || value instanceof Boolean)
        return value.toString();
    if (value instanceof String)
        return '\'' + value.toString() + '\'';
    if (value instanceof Iterable)
        return '[' + StreamSupport.stream(((Iterable<?>) value).spliterator(), false).map(v -> toCypher(v, config)).filter(Objects::nonNull).collect(Collectors.joining(",")) + ']';
    if (value.getClass().isArray())
        return '[' + Arrays.stream((Object[]) value).map(v -> toCypher(v, config)).filter(Objects::nonNull).collect(Collectors.joining(",")) + ']';
    if (value instanceof Node) {
        Node node = (Node) value;
        String labels = StreamSupport.stream(node.getLabels().spliterator(), false).map(l -> quote(l.name())).collect(Collectors.joining(":"));
        if (!labels.isEmpty())
            labels = ':' + labels;
        String var = cypherName(config, "node", () -> "", Util::quote);
        return '(' + var + labels + ' ' + toCypher(node.getAllProperties(), config) + ')';
    }
    if (value instanceof Relationship) {
        Relationship rel = (Relationship) value;
        String type = ':' + quote(rel.getType().name());
        String start = cypherName(config, "start", () -> toCypher(rel.getStartNode(), config), (s) -> '(' + quote(s) + ')');
        String relationship = cypherName(config, "relationship", () -> "", Util::quote);
        String end = cypherName(config, "end", () -> toCypher(rel.getEndNode(), config), (s) -> '(' + quote(s) + ')');
        return start + "-[" + relationship + type + ' ' + toCypher(rel.getAllProperties(), config) + "]->" + end;
    }
    if (value instanceof Map) {
        Map<String, Object> values = (Map<String, Object>) value;
        if (config.containsKey("keepKeys")) {
            values.keySet().retainAll((List<String>) (config.get("keepKeys")));
        }
        if (config.containsKey("skipKeys")) {
            values.keySet().removeAll((List<String>) (config.get("skipKeys")));
        }
        return '{' + values.entrySet().stream().map((e) -> Pair.of(e.getKey(), toCypher(e.getValue(), config))).filter((p) -> p.other() != null).sorted(Comparator.comparing(Pair::first)).map((p) -> quote(p.first()) + ":" + p.other()).collect(Collectors.joining(",")) + '}';
    }
    return null;
}
Also used : java.util(java.util) URLDecoder(java.net.URLDecoder) Pair(org.neo4j.helpers.collection.Pair) Function(java.util.function.Function) Supplier(java.util.function.Supplier) StringUtils(org.apache.commons.lang3.StringUtils) Node(org.neo4j.graphdb.Node) Matcher(java.util.regex.Matcher) Util.quote(apoc.util.Util.quote) Arrays.asList(java.util.Arrays.asList) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) StreamSupport(java.util.stream.StreamSupport) Math.toIntExact(java.lang.Math.toIntExact) Util(apoc.util.Util) Procedure(org.neo4j.procedure.Procedure) Description(org.neo4j.procedure.Description) StringResult(apoc.result.StringResult) Collectors(java.util.stream.Collectors) UserFunction(org.neo4j.procedure.UserFunction) Normalizer(java.text.Normalizer) URLEncoder(java.net.URLEncoder) Relationship(org.neo4j.graphdb.Relationship) Stream(java.util.stream.Stream) Name(org.neo4j.procedure.Name) Pattern(java.util.regex.Pattern) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Node(org.neo4j.graphdb.Node) Util(apoc.util.Util) Relationship(org.neo4j.graphdb.Relationship) Description(org.neo4j.procedure.Description) UserFunction(org.neo4j.procedure.UserFunction)

Example 7 with UserFunction

use of org.neo4j.procedure.UserFunction in project neo4j-apoc-procedures by neo4j-contrib.

the class Strings method regexGroups.

@UserFunction
@Description("apoc.text.regexGroups(text, regex) - return all matching groups of the regex on the given text.")
public List<List<String>> regexGroups(@Name("text") final String text, @Name("regex") final String regex) {
    if (text == null || regex == null) {
        return Collections.EMPTY_LIST;
    } else {
        final Pattern pattern = Pattern.compile(regex);
        final Matcher matcher = pattern.matcher(text);
        List<List<String>> result = new ArrayList<>();
        while (matcher.find()) {
            List<String> matchResult = new ArrayList<>();
            for (int i = 0; i <= matcher.groupCount(); i++) {
                matchResult.add(matcher.group(i));
            }
            result.add(matchResult);
        }
        return result;
    }
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) Arrays.asList(java.util.Arrays.asList) Description(org.neo4j.procedure.Description) UserFunction(org.neo4j.procedure.UserFunction)

Example 8 with UserFunction

use of org.neo4j.procedure.UserFunction in project neo4j-nlp by graphaware.

the class AnnotateFunction method getAnnotation.

@UserFunction("ga.nlp.processor.annotate")
@Description("Perform the annotation on the given text, returns the produced annotation domain")
public Map<String, Object> getAnnotation(@Name("text") String text, @Name("pipelineSpecification") Map<String, Object> specificationInput) {
    PipelineSpecification pipelineSpecification = PipelineSpecification.fromMap(specificationInput);
    String pipeline = getNLPManager().getPipeline(pipelineSpecification.getName());
    PipelineSpecification spec = getConfiguration().loadPipeline(pipeline);
    TextProcessor processor = getNLPManager().getTextProcessorsManager().getTextProcessor(spec.getTextProcessor());
    AnnotatedText annotatedText = processor.annotateText(text, "en", pipelineSpecification);
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
    return mapper.convertValue(annotatedText, Map.class);
}
Also used : PipelineSpecification(com.graphaware.nlp.dsl.request.PipelineSpecification) TextProcessor(com.graphaware.nlp.processor.TextProcessor) AnnotatedText(com.graphaware.nlp.domain.AnnotatedText) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) Description(org.neo4j.procedure.Description) UserFunction(org.neo4j.procedure.UserFunction)

Example 9 with UserFunction

use of org.neo4j.procedure.UserFunction in project neo4j-nlp by graphaware.

the class SentenceFunctions method nextTags.

@UserFunction("ga.nlp.sentence.nextTags")
@Description("Returns a list of Tag nodes that appear just after the given Tag in a sentence along with the frequency")
public List<Map<String, Object>> nextTags(@Name("from") Node from) {
    Map<Long, Integer> freqMap = new HashMap<>();
    Map<Long, Node> references = new HashMap<>();
    for (Relationship rel : from.getRelationships(Relationships.TAG_OCCURRENCE_TAG, Direction.INCOMING)) {
        Node tagOccurence = rel.getStartNode();
        int minPosition = (int) tagOccurence.getProperty(Properties.END_POSITION);
        Node sentence = tagOccurence.getSingleRelationship(Relationships.SENTENCE_TAG_OCCURRENCE, Direction.INCOMING).getStartNode();
        for (Relationship rel2 : sentence.getRelationships(Relationships.SENTENCE_TAG_OCCURRENCE, Direction.OUTGOING)) {
            Node occurence = rel2.getEndNode();
            int occPosition = (int) occurence.getProperty(Properties.START_POSITION);
            if (occPosition == (minPosition + 1)) {
                Node tag = occurence.getSingleRelationship(Relationships.TAG_OCCURRENCE_TAG, Direction.OUTGOING).getEndNode();
                Integer freq = freqMap.containsKey(tag.getId()) ? freqMap.get(tag.getId()) + 1 : 1;
                freqMap.put(tag.getId(), freq);
            }
        }
    }
    List<Map<String, Object>> response = new ArrayList<>();
    for (Long l : references.keySet()) {
        Map<String, Object> m = new HashMap<>();
        m.put("node", references.get(l));
        m.put("frequency", freqMap.get(l));
        response.add(m);
    }
    return response;
}
Also used : HashMap(java.util.HashMap) Node(org.neo4j.graphdb.Node) ArrayList(java.util.ArrayList) Relationship(org.neo4j.graphdb.Relationship) Map(java.util.Map) HashMap(java.util.HashMap) Description(org.neo4j.procedure.Description) UserFunction(org.neo4j.procedure.UserFunction)

Example 10 with UserFunction

use of org.neo4j.procedure.UserFunction in project neo4j-apoc-procedures by neo4j-contrib.

the class ExtractURL method parse.

@UserFunction("apoc.data.url")
@Description("apoc.data.url('url') as {protocol,host,port,path,query,file,anchor,user} | turn URL into map structure")
public Map<String, Object> parse(@Name("url") final String value) {
    if (value == null)
        return null;
    try {
        URL u = new URL(value);
        Long port = u.getPort() == -1 ? null : (long) u.getPort();
        return map("protocol", u.getProtocol(), "user", u.getUserInfo(), "host", u.getHost(), "port", port, "path", u.getPath(), "file", u.getFile(), "query", u.getQuery(), "anchor", u.getRef());
    } catch (MalformedURLException exc) {
        return null;
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) URL(java.net.URL) Description(org.neo4j.procedure.Description) UserFunction(org.neo4j.procedure.UserFunction)

Aggregations

UserFunction (org.neo4j.procedure.UserFunction)10 Description (org.neo4j.procedure.Description)7 Arrays.asList (java.util.Arrays.asList)2 ThreadLocalRandom (java.util.concurrent.ThreadLocalRandom)2 Matcher (java.util.regex.Matcher)2 Pattern (java.util.regex.Pattern)2 Node (org.neo4j.graphdb.Node)2 Relationship (org.neo4j.graphdb.Relationship)2 ComponentInjectionException (org.neo4j.kernel.api.exceptions.ComponentInjectionException)2 StringResult (apoc.result.StringResult)1 Util (apoc.util.Util)1 Util.quote (apoc.util.Util.quote)1 AnnotatedText (com.graphaware.nlp.domain.AnnotatedText)1 PipelineSpecification (com.graphaware.nlp.dsl.request.PipelineSpecification)1 TextProcessor (com.graphaware.nlp.processor.TextProcessor)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 Math.toIntExact (java.lang.Math.toIntExact)1 MethodHandle (java.lang.invoke.MethodHandle)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1