question stringlengths 11 28.2k | answer stringlengths 26 27.7k | tag stringclasses 130
values | question_id int64 935 78.4M | score int64 10 5.49k |
|---|---|---|---|---|
What is the best way to drop a collection in MongoDB?
I am using the following:
db.collection.drop()
As described in the manual:
db.collection.drop()
Removes a collection from the database. The method also removes any
indexes associated with the dropped collection. The method provides a
wrapper around the drop co... | So either of these are valid ways to do it:
mongo <dbname> --eval 'db.<collection>.drop()'
# ^^^^^^^^ ^^^^^^^^^^^^
db.<collection>.drop()
# ^^^^^^^^^^^^
For example, for a collection mycollection in a database mydb you would say:
mongo mydb --eval 'db.mycollection.drop()'
db.mycollection.drop()
... | MongoDB | 30,948,151 | 75 |
I know this may be a silly question, but I read on an e-book that there is an upsert option in MongoDB insert. I couldn't find proper documentation about this. Can someone educate me about this?
| Since upsert is defined as operation that "creates a new document when no document matches the query criteria" there is no place for upsertsin insert command. It is an option for the update command. If you execute command like below it works as an update, if there is a document matching query, or as an insert with docu... | MongoDB | 19,974,216 | 75 |
can I use combination of OR and AND in mongodb queries?
the code below doesn't work as expected
db.things.find({
$and:[
{$or:[
{"first_name" : "john"},
{"last_name" : "john"}
]},
{"phone": "12345678"}
]});
... | db.things.find({
$and: [
{
$or: [
{"first_name": "john"},
{"last_name": "john"}
]
},
{
"Phone": "12345678"
}
]
})
AND takes an array of 2 expressions OR , phone.
OR takes an array of 2 expressions first_name , l... | MongoDB | 11,196,101 | 75 |
Does MongoDB offer a find or query method to test if an item exists based on any field value? We just want check existence, not return the full contents of the item.
| Since you don't need the count, you should make sure the query will return after it found the first match. Since count performance is not ideal, that is rather important. The following query should accomplish that:
db.Collection.find({ /* criteria */}).limit(1).size();
Note that find().count() by default does not hono... | MongoDB | 8,389,811 | 75 |
When installing MongoDb, I get the option to install it as a service. What does that mean? If I don't select that option, what difference would it make? Also, selecting "install as a service" will bring up additional options, such as "Run service as a network service user" or "run service as a local or domain user". Wh... | I'm speaking in the perspective of Windows development, but the concepts are similar with other Operating Systems, such as Linux.
What are services?
Services are application types that run in the system's background. These are applications such as task schedulers and event loggers. If you look at the Task Manager > P... | MongoDB | 52,068,925 | 74 |
I'm using node.js and Mongo.db (I'm newly on Mongo). I have a document like this:
Tag : {
name: string,
videoIDs: array
}
The idea is, the server receives a JSON like
JSON: {
name: "sport",
videoId: "34f54e34c"
}
with this JSON, it has to find the tag with the same name and check if in the array it ha... | You can use $addToSet operator to check exist before append element into array.
db.tags.update(
{name: 'sport'},
{$addToSet: { videoIDs: "34f54e34c" } }
);
In this update statement example, mongoDB will find the TAG document which matches name == sport, and then check whether the videoIDs array contains 34f54e... | MongoDB | 38,970,835 | 74 |
How would I get an array containing all values of a certain field for all of my documents in a collection?
db.collection:
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be6"), "x" : 1 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be7"), "x" : 2 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be8"), "x" : 3 }
{ "_id" : ObjectId("51a7... | db.collection.distinct('x')
should give you an array of unique values for that field.
| MongoDB | 23,273,123 | 74 |
If I delete the 3.1G journal file, sudo service mongodb restart will fail. However, this file is taking too much space. How can I solve this problem? How can I remove it?
bash$ du -sh /var/lib/mongodb/*
4.0K _tmp
65M auction_development.0
128M auction_development.1
17M auction_development.ns
3.1G journal
4.0K ... | TL;DR: You have two options. Use the --smallfiles startup option when starting MongoDB to limit the size of the journal files to 128MB, or turn off journalling using the --nojournal option. Using --nojournal in production is usually a bad idea, and it often makes sense to use different write concerns also in developmen... | MongoDB | 19,533,019 | 74 |
Using mongoskin, I can do a query like this, which will return a cursor:
myCollection.find({}, function(err, resultCursor) {
resultCursor.each(function(err, result) {
}
}
However, I'd like to call some async functions for each document, and only move on to the next item on the cursor after this has called... | A more modern approach that uses async/await:
const cursor = db.collection("foo").find({});
while(await cursor.hasNext()) {
const doc = await cursor.next();
// process doc here
}
Notes:
This may be even more simple to do when async iterators arrive.
You'll probably want to add try/catch for error checking.
The co... | MongoDB | 18,119,387 | 74 |
Consider following is the Node.js code:
function My_function1(_params) {
db.once('open', function (err){
//Do some task 1
});
}
function My_function2(_params) {
db.once('open', function (err){
//Do some task 2
});
}
See the link for best practice, which says not to close any connections
https://grou... | You open a Db connection once with MongoClient and reuse it across your application. If you need to use multiple db's you use the .db function on the Db object to work on a different db using the same underlying pool of connections. A pool is kept to ensure a single blocking operation cannot freeze up your node.js appl... | MongoDB | 14,495,975 | 74 |
I really like MongoDB's automatically generated ids. They are really useful.
However, is it save to use them publicly?
Let's say there is a posts collection, and the /posts page that takes id paramater (something like /posts/4d901acd8df94c1fe600009b) and displays info about it.
This way the user/hacker will know the r... | The ObjectID documentation states that the automatically generated IDs include a 3-byte machine ID (presumably a hash of the MAC address). It's not inconceivable that someone could figure out things about your internal network by comparing those three bytes in various ids, but unless you're working for the Pentagon tha... | MongoDB | 4,587,523 | 74 |
I have two collections
User
{
"_id" : ObjectId("584aac38686860d502929b8b"),
"name" : "John"
}
Role
{
"_id" : ObjectId("584aaca6686860d502929b8d"),
"role" : "Admin",
"userId" : "584aac38686860d502929b8b"
}
I want to join these collection based on the userId (in role collection) - _id ( in user colle... | You can use $toObjectId aggregation from mongodb 4.0 which converts String id to ObjectId
db.role.aggregate([
{ "$lookup": {
"from": "user",
"let": { "userId": "$_id" },
"pipeline": [
{ "$addFields": { "userId": { "$toObjectId": "$userId" }}},
{ "$match": { "$expr": { "$eq": [ "$userId", "$$u... | MongoDB | 41,093,647 | 73 |
Is it necessary to give 'worker' information in Procfile? If yes then what it is actually? I have already added web: node server/server.js detail in the Procfile.
|
Procfile is a mechanism for declaring what commands are run by your application’s dynos on the Heroku platform.
From Process Types and the Procfile, which is a good introduction, but basically you use the Procfile to tell Heroku how to run various pieces of your app. The part to the left of the colon on each line is ... | MongoDB | 16,128,395 | 73 |
I am in the middle of building a new app which will have very similar features to Facebook and although obviously it wont ever have to deal with the likes of 400,000,000 million users it will still be used by a substantial user base and most of them will demand it run very very quickly.
I have extensive experience with... | I would suggest doing some testing with MySQL and with Cassandra. When we had to make a choice between PostgreSQL and MongoDB in one of my jobs, we compared query time on millions of records in both and found out that with about 10M records Postgres would provide us with adequate response times.
We knew that we wouldn... | Neo4j | 2,581,465 | 11 |
What's the difference between these two lines?
call apoc.periodic.iterate("MATCH (n:Nodes) return n", "DETACH DELETE n", {batchSize:10000, iterateList:true})"
call apoc.periodic.commit("match (n:Nodes) limit {limit} detach delete n RETURN count(*)",{limit:10000})
What is the best way to delete lots of nodes?
| The procedure apoc.periodic.iterate takes two queries :
the first one to create a set of nodes in your example
the second one will be executed for each result of the first query
So in your example your match all the Node of your database, and then you delete them with a batch size of 10000.
The procedure apoc.period... | Neo4j | 51,171,928 | 11 |
Most of the reasons for using a graph database seem to be that relational databases are slow when making graph like queries.
However, if I am using GraphQL with a data loader, all my queries are flattened and combined using the data loader, so you end up making simpler SELECT * FROM X type queries instead of doing any ... | GraphQL doesn't negate the need for graph databases at all, the connection is very powerful and makes GraphQL more performant and powerful.
You mentioned:
However, if I am using GraphQL with a data loader, all my queries are flattened and combined using the data loader, so you end up making simpler SELECT * FROM X typ... | Neo4j | 50,134,500 | 11 |
Getting results on a pandas dataframe from a cypher query on a Neo4j database with py2neo is really straightforward, as:
>>> from pandas import DataFrame
>>> DataFrame(graph.data("MATCH (a:Person) RETURN a.name, a.born LIMIT 4"))
a.born a.name
0 1964 Keanu Reeves
1 1967 Carrie-Anne Moss
... | You can use DataFrame.iterrows() to iterate through the DataFrame and execute a query for each row, passing in the values from the row as parameters.
for index, row in df.iterrows():
graph.run('''
MATCH (a:Label1 {property:$label1})
MERGE (a)-[r:R_TYPE]->(b:Label2 {property:$label2})
''', parameters... | Neo4j | 45,738,180 | 11 |
I am using Neo4j CE 3.1.1 and I have a relationship WRITES between authors and books. I want to find the N (say N=10 for example) books with the largest number of authors. Following some examples I found, I came up with the query:
MATCH (a)-[r:WRITES]->(b)
RETURN r,
COUNT(r) ORDER BY COUNT(r) DESC LIMIT 10
When I exec... | Aggregations only have context based on the non-aggregation columns, and with your match, a unique relationship will only occur once in your results.
So your first query is asking for each relationship on a row, and the count of that particular relationship, which is 1.
You might rewrite this in a couple different ways... | Neo4j | 42,238,183 | 11 |
Everytime I try to divide something in neo4j, I keep getting zero. I am using the following query:
MATCH (m:Member)-[:ACTIVITY{issue_d:"16-Jan"}]->(l:Loan)
MATCH (m)-[:ACTIVITY]->(p:Payments)
WHERE l.installment<1000 AND p.total_pymnt>0
RETURN (l.funded_amnt-p.total_pymnt),(l.funded_amnt-p.total_pymnt)/(l.funded_amnt)... | Multiply your numerator by 1.0.
MATCH (m:Member)-[:ACTIVITY {issue_d:"16-Jan"}]->(l:Loan)
MATCH (m)-[:ACTIVITY]->(p:Payments)
WHERE l.installment < 1000 AND p.total_pymnt > 0
RETURN (l.funded_amnt - p.total_pymnt), ((l.funded_amnt - p.total_pymnt) * 1.0) / l.funded_amnt, l.funded_amnt, p.total_pymnt, m.member_id
LIMIT ... | Neo4j | 37,599,289 | 11 |
I'm trying to import a local csv file but I have got InvalidSyntax Error.
LOAD CSV WITH HEADERS FROM file:C:/csv/user.csv
Invalid input '/' (line 1, column 35 (offset: 34))
"LOAD CSV WITH HEADERS FROM file:C:/csv/user.csv"
| You need to put the filename in quotes, and add a few more slashes:
LOAD CSV WITH HEADERS FROM "file:///C:/csv/user.csv"
Full documentation here.
| Neo4j | 37,299,077 | 11 |
My local Neo4j has a lot of transaction logs in data/graph.db:
251M 3 Sep 16:44 neostore.transaction.db.0
255M 3 Sep 20:01 neostore.transaction.db.1
255M 3 Sep 23:20 neostore.transaction.db.2
251M 4 Sep 19:34 neostore.transaction.db.3
250M 4 Sep 22:16 neostore.transaction.db.4
134M 5 Sep 05:02 neostore.transactio... | If you database in good condition you can delete all neostore.transaction.db.x files, but I recommend to you backup them.
Stop Neo4j
Delete neostore.transaction.db.x files
Start Neo4j
| Neo4j | 32,442,951 | 11 |
I'm trying to access neo4j running on an aws ec2 instance from the command line where I get authorisation errors. I've enabled org.neo4j.server.webserver.address=0.0.0.0 and get a 503 error on the first statement and the same errors for the rest using the ec2 host name.
ubuntu@ip-10-0-0-192:/etc/neo4j$ curl http://loc... | You need to provide authorization header in your request
Authorization: Basic bmVvNGo6bmVvNGo=
curl --header "Authorization: Basic bmVvNGo6bmVvNGo=" http://localhost:7474
bmVvNGo6bmVvNGo= is default Neo4j password: neo4j
by @michael-hunger
note: For the auth APIs you still need authorization.
curl -u neo4j:password ... | Neo4j | 31,966,591 | 11 |
Anybody know of any Graph DB's that support time series data?
Ideally we're looking for one that will scale well, and ideally use Cassandra or HBase as their persistent store.
| Why would you want to do that? Best practice would be to store the dependency graph (in other words, the "Model" of the time series data) in a graphdb, but the actual time series in something more suited to that. Eg a KV store or a log-specific tool like Splunk...
See the KNMI (Dutch Weather Service) example for a case... | Neo4j | 31,129,492 | 11 |
How can i get node by propery value? I mean something like that:
I'll tried
match (n) where has (n.name = 'Mark')
return n
But it's incorrect.
And also How can i find node with max property value. I have nodes with property "VIEWS" and i want see node with max views.
| So close...
MATCH (n)
WHERE n.name = 'Mark'
RETURN n
It is better to include a node label if you have one that will serve to segregate your node from other nodes of different types. This way if you have an index on the name property and label combination you will get better search responsiveness. For instance, you... | Neo4j | 29,382,025 | 11 |
I have nodes without label but a property NodeType
Is there a way to set the label of those nodes with the value of the NodeType property?
Thanks!
| No, currently there is no possibility to define a label with a variable.
You'll have to do it in your application by fetching all nodes that you want to add a label on it and sending a Cypher Query to add this label.
A quick example in PHP :
$nodes = $client->sendCypherQuery('MATCH (n) WHERE n.nodeType = "MyType" RETU... | Neo4j | 26,536,573 | 11 |
Previously I had a problem when making a 'backup' as shown in this question where I get an error when trying to restore the database because I did a copy when the database was running.
So I did an experiment with a new database from another computer (this time with ubuntu) I tried this:
I created some nodes and relat... | Online backup, in a sense of taking a consistent backup while Neo4j is running, is only available in Neo4j enterprise edition. Enterprise edition's backup also features a verbose consistency check of the backup, something you do not get in community either.
The only safe option in community edition is to shutdown Neo4j... | Neo4j | 25,567,744 | 11 |
How to set up the following in neo4j community edition version 2.x
failover
master-slave setup
cluster
Is HA (high availability) is different from cluster setup in neo4j?
| HA, failover and clustering are only available in Neo4j's enterprise edition. For detailed documentation please refer to http://docs.neo4j.org/chunked/stable/ha.html
Neo4j enterprise edition is licensed open source via AGPL or via commercial licensing provided by Neo Technology. The commercial licenses come with suppor... | Neo4j | 24,646,962 | 11 |
I'm looking at visualization options for a graph database project that I have coming up. Part of the job is to provide an interactive visualization of the data for public website visitors.
The standard Neo4j Server Web Interface does all I would need it to and more. I was wandering if I could simply embed it in a web... | The Neo4j browser is an Angular.js application using d3.js as visualization. The code is all open source an on https://github.com/neo4j/neo4j/tree/2.2/community/browser/lib/visualization so you can check it out there.
In general http://maxdemarzi.com is a good source for visualization blog posts as is http://neo4j.org/... | Neo4j | 21,506,825 | 11 |
In this cypher query,the longest path/paths between nodes which have relationship with STATUS="on" property with each other,will be returned,but I want to get also the last node of the path/paths.
query:
START n=node(*)
MATCH p=n-[rels:INCLUDE*]->m
WHERE ALL (rel IN rels
WHERE rel.status='on')
WITH COLLECT(p) AS p... | This would give two arrays. The first array is the last item in each path, the second is each path:
START n=node(*)
MATCH p=n-[rels:INCLUDE*]->m
WHERE ALL (rel IN rels
WHERE rel.status='on')
WITH COLLECT(p) AS paths, MAX(length(p)) AS maxLength
WITH FILTER(path IN paths WHERE length(path)= maxLength) AS longestPa... | Neo4j | 19,772,472 | 11 |
I need to delete some node properties from my graph. Following the cypher guidelines I have tried the following:
START n=node(1)
DELETE n.property
RETURN n
I get an error message:
Expression `Property` yielded `true`. Don't know how to delete that.
I can replicate this on console.neo4j.org. How are you supposed to de... | What version of Neo4j are you using? Since Neo4j 2.0 (I'm not sure what milestone exactly, tried it with M03), properties are not "deleted" anymore but "removed":
START n=node(1)
REMOVE n.property
RETURN n
Should work with Neo4j 2.x.
This is also reflected in the documentation. On the right side of the page (perhaps a... | Neo4j | 18,010,551 | 11 |
I try to use n4j in my app, but I have problem with big log files. Are they necessary or is there some way to reduce the number and size of them?
At the moment I see files like:
nioneo_logical.log.v0
nioneo_logical.log.v1
nioneo_logical.log.v2
etc
and they are ~26MB each (over 50% of neo4j folder).
| These files are created whenever the logical logs are rotated.
You can configure rules for them in the server properties file.
See details here: http://docs.neo4j.org/chunked/stable/configuration-logical-logs.html
You can safely remove them (but only the *.v*) if your database is shutdown and in a clean state. Don't re... | Neo4j | 14,696,819 | 11 |
How can i get the current running neo4j-server version (or in general server informations) via REST? Is there any "/status" URI or something similar?
| Try this one,
Get http://localhost:7474/db/manage/server/version
This will give you a json response like
{
"edition" : "community",
"version" : "2.3.3"
}
| Neo4j | 10,881,485 | 11 |
This is how you can sort (order) results from Neo4j graph using Gremlin:
g.v(id).out('knows').sort{it.name}
or
g.v(id).out('knows').sort{a,b -> a.name <=> b.name}
This is how to limit result using offset/skip and limit:
g.v(id).out('knows')[0..9]
However if you combine both sort and limit
g.v(id).out('knows').sort{... | It took me a while to figure out that native Groovy methods like sort do not return Pipes, but iterators, iterables, etc. As such, to convert one of these objects back into a Pipeline flow you need to use _():
g.v(id).out('knows').sort{it.name}._()[0..9]
| Neo4j | 10,367,331 | 11 |
I'm playing around with neo4j, and I was wondering, is it common to have a type property on nodes that specify what type of Node it is? I've tried searching for this practice, and I've seen some people use name for a purpose like this, but I was wondering if it was considered a good practice or if indexes would be the ... | Labels have been added to neo4j 2.0. They fix this problem.
You can create nodes with labels:
CREATE (me:American {name: "Emil"}) RETURN me;
You can match on labels:
MATCH (n:American)
WHERE n.name = 'Emil'
RETURN n
You can set any number of labels on a node:
MATCH (n)
WHERE n.name='Emil'
SET n :Swedish:Bossman
RETUR... | Neo4j | 10,239,709 | 11 |
I'm getting ready to start a project where I will be building a recommendation engine for restaurants. I have been waffling between neo4j (graph db) and mongodb (document db). my nodes/documents will be things like restaurant and person. i know i will want some edges, something like person->likes->restaurant, or per... | Neo4j Spatial introduces a Spatial RTree (or other means) index that is part of the graph itself. That means, even disconnected domain entities will be found via the spatial search, if you index them (that is relationships will connect the Spatial index to the Restaurants). Also, this is flexible enough that you can co... | Neo4j | 9,605,271 | 11 |
I wonder what the REST API clients are available for using from Ruby (not JRuby, so native bindings are not an option)?
Ideally, I would want the API similar to the neo4j gem or ActiveRecord (validations, migrations, observers etc).
Currently available (REST) tooling doesn't even come close to what we have, for example... | The short answer is that there is no any mature ActiveModel-like gems for RESTful neo4j.
The most common scenario is to just use Neography.
| Neo4j | 8,335,136 | 11 |
Has anyone gone any experience of using Neo4j with terabyte sized datasets? I would like to hear about your expereinces with how Neo4j performs
| As long as your disk is large and fast enough and your memory allows for caching of the relevant (hot) portion of your data, you shouldn't run into issues.
There are optimizations for tuning the Neo4j datastore to specific needs.
Otherwise it depends on the kind of your dataset. Query performance shouldn't be an issue,... | Neo4j | 5,680,169 | 11 |
I recently started researching database features of databases.
At the moment I'm looking into Neo4j Graph database.
Unfortunately, I can't find every bit of information I need.
I found most information except the following:
Supporting datatypes? (Integer,
Max. database size?
Max. nodes in db?
Max. relations in db?
| The supported datatypes:
boolean or boolean[]
byte or byte[]
short or short[]
int or int[]
long or long[]
float or float[]
double or double[]
char or char[]
java.lang.String or String[]
Source: Neo4j API docs
There's no limit on database size, but the current release (1.2) has limitations on the number of nodes, rela... | Neo4j | 5,152,164 | 11 |
I have a cypher script file and I would like to run it directly.
All answers I could find on SO to the best of my knowledge use the command neo4j-shell which in my version (Neo4j server 3.5.5) seems to be deprecated and substituted with the command cyphershell.
Using the command sudo ./neo4j-community-3.5.5/bin/cypher-... | Use cypher-shell -f yourscriptname. Check with --help for more description.
| Neo4j | 56,038,659 | 10 |
what I did
neo4j console
(work fine)
ctrl-C
upon restarting I have message above.
I delete /var/lib/neo4j/data/databases/graph.db/store_lock
then I have
Externally locked: /var/lib/neo4j/data/databases/graph.db/neostore
Is there any way of cleaning lock ? (short of reinstalling)
| Killing the Java process and deleting the store_lock worked for me:
Found the lingering process,
ps aux | grep "org.neo4j.server"
killed it,
kill -9 <pid-of-neo4js-java-process>
and deleted
sudo rm /var/lib/neo4j/data/databases/graph.db/store_lock
Allegedly, just killing the lingering process may do the trick but I ... | Neo4j | 44,757,181 | 10 |
Has there been any update to the syntax of an IF/ELSE statement in Cypher?
I know about CASE and the FOREACH "hacks" but they are so unsightly to read :)
I was wanting to do something with optional parameters such as:
CASE WHEN exists($refs.client) THEN MATCH (cl:client {uuid: $refs.client}) END
...
// and later use i... | APOC Procedures just updated with support for conditional cypher execution. You'll need version 3.1.3.7 or greater (if using Neo4j 3.1.x), or version 3.2.0.3 or greater (if using Neo4j 3.2.x).
Here's an example of some of the cases you mentioned, using the new procedures:
CALL apoc.when($refs.client IS NOT NULL,
"MAT... | Neo4j | 43,481,472 | 10 |
I have a graph database that maps out connections between buildings and bus stations, where the graph contains other connecting pieces like roads and intersections (among many node types).
What I'm trying to figure out is how to filter a path down to only return specific node types. I have two related questions that I'... |
To get the distinct labels along matching paths:
MATCH p=(a:Building)-[:CONNECTED_TO*..5]-(b:Bus)
WITH NODES(p) AS nodes
UNWIND nodes AS n
WITH LABELS(n) AS ls
UNWIND ls AS label
RETURN DISTINCT label;
To return the nodes that have the Street label.
MATCH p=(a:Building)-[r:CONNECTED_TO*]-(b:Bus)
WITH NODES(p) AS node... | Neo4j | 39,733,178 | 10 |
I am working on migration of data from postgres to Graph Database manually.
I have wrote script below:
import psycopg2
from py2neo import authenticate, Graph
authenticate("localhost:7474", "neo4j", "password")
n4j_graph = Graph("http://localhost:7474/db/data/")
try:
conn=psycopg2.connect("dbname='db_name' user='... | I had this problem too. In my case I was looking at the py2neo v2 documentation but on my machine was installed py2neo v3. You should check your py2neo version and replace .cyper({query}) with .run({query})
The previous version of py2neo allowed Cypher execution through Graph.cypher.execute(). This facility is now ins... | Neo4j | 37,530,309 | 10 |
I have recently installed Neo4j 3.0, and since I need to enable outside access, I need the configuration file, and where in the 2.3.3 the configuration files were located in within the /var/lib/neo4j/ structure.
I am not able to locate them anywhere in the 3.0 version. I know it have changed name to neo4j.conf.
My fold... | [UPDATED]
According to the 3.0.0 Operations Manual, the default location of the config file for "Debian" is:
/etc/neo4j/neo4j.conf
| Neo4j | 36,919,507 | 10 |
I try to import CSV in a Neo4j Database and I have a problem.
On my desktop computer (windows 7, java 1.8.0_40-b25), the LOAD CSV works great.
But on the server (windows 2012 R2, java 1.8.0_65-b17), i have this error message "URI is not hierarchical".
I try to put the data on C:, F: ... no change.
Here's the code :
US... | Are you using 2.3.0 Community Edition?
try:
USING PERIODIC COMMIT 10000 LOAD CSV FROM
'file:///F:\\Neo4JData\\Destination.csv
| Neo4j | 33,481,042 | 10 |
I need to group the data from a neo4j database and then to filter out everything except the top n records of every group.
Example:
I have two node types : Order and Article. Between them there is an "ADDED" relationship. "ADDED" relationship has a timestamp property. What I want to know (for every article) is how many... | Try
MATCH (o:Order)-[r:ADDED]->(a:Article)
WITH o, r, a
ORDER BY o.oid, r.t
WITH o, COLLECT(a)[..2] AS topArticlesByOrder UNWIND topArticlesByOrder AS a
RETURN a.aid AS articleId, COUNT(*) AS count
Results look like
articleId count
8 6
2 2
4 5
7 2
3 3... | Neo4j | 32,951,651 | 10 |
I was wondering if I could run multiple standalone instances of neo4j on a single machine. I understand that I could configure multiple instances as HA cluster (here), but that is not my intention, I only need two totally different and independent instances of neo4j on my machine (Which is a Mac OSX if that makes a dif... | The most easy way is to unpack the neo4j installation into two different locations. In one of the locations you need to change the port settings in conf/neo4j-server.properties and, if neo4j-shell is enabled conf/neo4j.properties as well.
Also consider to set dbms.pagecache.memory to a reasonable value. By default eac... | Neo4j | 32,548,590 | 10 |
I want to delete an element from an array property on a node using Cypher.
I know the value of the element I want to delete, but not its index.
e.g. suppose I have a node like
({some_array: ["apples", "oranges"]})
I want a query like (pseudocode):
MATCH (n)
REMOVE "oranges" IN n.some_array
| Cypher doesn't have functions for mutating arrays, but you can create a new array with "oranges" removed using FILTER:
MATCH (n)
WHERE HAS(n.some_array)
SET n.array = FILTER(x IN n.some_array WHERE x <> "oranges");
| Neo4j | 31,953,794 | 10 |
is there pagination support for custom queries in SDN4?
If yes, how does it work?
If no, is there a workarround?
I have the following Spring Data Neo4j 4 repository:
@Repository
public interface TopicRepository
extends GraphRepository<Topic>,IAuthorityLookup {
// other methods omitted
@Query("MATCH (t:Topic)... | This is now allowed using Sort or Pageable interfaces in your query, and was fixed in DATAGRAPH-653 and marked as fixed in version 4.2.0.M1 (currently in pre-release).
Queries such as the following are possible:
@Query("MATCH (movie:Movie {title={0}})<-[:ACTS_IN]-(actor) RETURN actor")
List<Actor> getActorsThatActInMov... | Neo4j | 30,624,435 | 10 |
Currently I use Neo4j 2.2.0-RC01. It has basic Auth enable as default. How can I disable the default Basic Auth on Neo4j 2.2.0-RC01?
| In file conf/neo4j-server.properties, change the dbms.security.auth_enabled to false and restart Neo4j:
# Require (or disable the requirement of) auth to access Neo4j
dbms.security.auth_enabled=false
| Neo4j | 29,096,616 | 10 |
Is it possible to extract in a single cypher query a limited set of nodes and the total number of nodes?
match (n:Molecule) with n, count(*) as nb limit 10 return {N: nb, nodes: collect(n)}
The above query properly returns the nodes, but returns 1 as number of nodes. I certainly understand why it returns 1, since the... | The following query returns the counter for the entire number of rows (which I guess is what was needed). Then it matches again and limits your search, but the original counter is still available since it is carried through via the WITH-statement.
MATCH
(n:Molecule)
WITH
count(*) AS cnt
MATCH
(n:Molecule... | Neo4j | 27,805,248 | 10 |
I’m trying to use LOAD CSV to create nodes with the labels being set to values from the CSV. Is that possible? I’m trying something like:
LOAD CSV WITH HEADERS FROM 'file:///testfile.csv' AS line
CREATE (x:line.label)
...but I get an invalid syntax error. Is there any way to do this?
| bicpence,
First off, this is pretty easy to do with a Java batch import application, and they aren't hard to write. See this batch inserter example. You can use opencsv to read your CSV file.
If you would rather stick with Cypher, and if you have a finite set of labels to work with, then you could do something like thi... | Neo4j | 24,992,977 | 10 |
Is it possible to change a label on a node using Cypher?
I have a node with label Book, as shown below. I want to change the Book label to DeletedBook.
(u:Person)-[r]-(b:Book{id:id1})
(u:Person)-[r]-(b:DeletedBook{id:id1})
| You can do that using REMOVE on the Book label and SET on the new label:
MATCH (p:Person)-[r]-(b:Book {id: id1})
REMOVE b:Book
SET b:DeletedBook
RETURN b
You should check out the Neo4j Cypher Refcard for a complete reference to Cypher 2.x.
| Neo4j | 24,056,127 | 10 |
I have stored a double (-0.1643) as string ("-0.1643") in a property on a neo4j relationship.
If I try to filter on this value with a numeric comparison:
MATCH (n1:Node)-[r:RELATION]-(n2:Node)
WHERE r.number < -0.1 RETURN n1, n2
Cypher throws an error:
Don't know how to compare that. Left: "-0.1643" (String); Right: ... | Check out release 2.0.2. It added to type functions, "toInt, toFloat, toStr". It looks like toDouble doesn't exist, but perhaps float is precise enough for you?
http://www.neo4j.org/release-notes#2.0.2
| Neo4j | 21,349,366 | 10 |
Under Neo4j v1.9.x, I used the following sort of code.
private Category CreateNodeCategory(Category cat)
{
var node = client.Create(cat,
new IRelationshipAllowingParticipantNode<Category>[0],
new[]
{
new IndexEntry(NeoConst.IDX_Category)
{
... | First up, for Neo4j 2 and onwards, you always need to start with the frame of reference "how would I do this in Cypher?". Then, and only then, do you worry about the C#.
Now, distilling your question, it sounds like your primary goal is to create a node, and then return a reference to it for further work.
You can do th... | Neo4j | 19,534,511 | 10 |
In the below query, does the 2nd match pattern john-[r?:HAS_SEEN]->(movie) run on the result of the first match john-[:IS_FRIEND_OF]->(user)-[:HAS_SEEN]->(movie) . I am trying to understand if this is similar to the unix pipe concept i.e. the result of the 1st pattern is the input to the 2nd pattern.
start john=node(1)... | I don't think I would compare multiple MATCH clauses to the UNIX pipes concept. Using multiple, comma-separated matches is just a way of breaking out of the 1-dimensional constraint of writing relationships with a single sentence. For example, the following is completely valid:
MATCH a--b,
b--c,
c--d,
... | Neo4j | 16,466,625 | 10 |
I've been recently exposed to the world of graph databases. Its quite an interesting paradigm shift for an old relational dog like me.
Also quite recently, I've been tinkering with liquibase and its been quite a neat tool in managing databases.
So, two worlds collide and I was just wondering if there are any tools... | Liquigraph exists now and although still quite new, the author is very receptive to feedback and is actively working on the project.
| Neo4j | 15,312,760 | 10 |
I'm working on a project where I have to deal with graphs...
I'm using a graph to get routes by bus and bike between two stops.
The fact is,all my relationship contains the time needed to go from the start point of the relationship and the end.
In order to get the shortest path between to node, I'm using the shortest ... | In cypher, to get all paths between two nodes not linked by a relationship, and sort by a total in a weight, you can use the reduce function introduced in 1.9:
start a=node(...), b=node(...) // get your start nodes
match p=a-[r*2..5]->b // match paths (best to provide maximum lengths to prevent queries from running awa... | Neo4j | 14,814,124 | 10 |
I had an embedded neo4j server with admin console working within a Play 2.0.1 application. I recently upgraded to the release candidate for compatibilities with DeadBolt and found that the application no longer runs.
To start the server I was doing the following:
graphDb = (GraphDatabaseAPI) new GraphDatabaseFactor... | With regard to the Neo4j lifecycle exception that gets thrown because Play 2.1's newer version of logback is not compatible with Neo4j's. I ran into this issue and ended up just overriding Play's logback to an older, compatible version by putting this in my Build.scala's project dependencies:
"ch.qos.logback" % "logbac... | Neo4j | 14,373,029 | 10 |
I am trying to use dBpedia with neo4j ontop of ruby on rails.
Assuming I have installed neo4j and downloaded one of the dBpedia datasets.
How do I import the dbpedia dataset into neo4j ?
| The simplest way to load dbpedia into Neo4j is to use the dbpedia4neo library. This is a Java library, but you don't need to know any Java because all you need to do is run the executable.
You could rewrite this in JRuby if you want, but regular Ruby won't work because it relies on Blueprints, a Java library with no R... | Neo4j | 12,212,015 | 10 |
In neo4j should all nodes connect to node 0 so that you can create a traversal that spans across all objects? Is that a performance problem when you get to large datasets? If so, how many nodes is too much? Is it ok not to have nodes connect to node 0 if I don't see a use case for it now, assuming I use indexes for ... | There is no need or requirement to connect everything to the root node. Indexes work great in finding starting points for your traversal. If you have say less then 5000 nodes connected to a starting node (like the root node), then a relationship scan is cheaper than an index lookup.
To judge what is better, you need to... | Neo4j | 12,186,803 | 10 |
I am trying to load all my Neo4j DB to the RAM so querying will work faster. When passing the properties map to the graph creation, I do not see the process taking more space in memory as it did before, and it is also not proportional to the space of files at disk.
What could be the problem? and how can it be fixed....... | Neo4j loads all the data lazily, meaning it loads them into memory at first access. The caching option is just about the GC strategy, so when (or if) the references will be GCed. To load the whole graph into memory, your cache type must be strong and you need to traverse the whole graph once. You can do it like this:
/... | Neo4j | 9,995,949 | 10 |
The class GraphDatabaseService seems not provide any method to drop/clear the database. It there any other means to drop/clear the current embedded database with Java?
| Just perform a GraphDatabaseService.shutdown() and after it has returned, remove the database files (using code like this).
You could also use getAllNodes() to iterate over all nodes, delete their relationships and the nodes themselves. Maybe avoid deleting the reference node.
If your use case is testing, then you coul... | Neo4j | 5,335,951 | 10 |
This is my source code of Main.java. It was grabbed from neo4j-apoc-1.0 examples. The goal of modification to store 1M records of 2 nodes and 1 relation:
package javaapplication2;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.g... | this is a configuration issue on Windows, where Neo4j cannot use memory mapped buffers. Instead, a Java Buffer on the heap is created. In 1.0 this buffer was 470MB per default, which is more than the default heap for the Windows JVM. You have two options:
Switch to APOC 1.1-SNAPSHOT instead of 1.0 in your pom.xml whic... | Neo4j | 2,927,329 | 10 |
I'm pretty sure the following query used to work for me on Presto:
select segment, sum(count)
from modeling_trends
where segment='2557172' and date = '2016-06-23' and count_time between '2016-06-23 14:00:00.000' and '2016-06-23 14:59:59.000';
group by 1;
now when I run it (on Presto 0.147 on EMR) I get an error of try... | Unlike some other databases, Trino doesn't automatically convert between varchar and other types, even for constants. The cast works, but a simpler way is to use the type constructors:
WHERE segment = '2557172'
AND date = date '2016-06-23'
AND count_time BETWEEN timestamp '2016-06-23 14:00:00.000' AND timestamp '20... | Presto | 38,037,713 | 59 |
I have external tables created in AWS Athena to query S3 data, however, the location path has 1000+ files. So I need the corresponding filename of the record to be displayed as a column in the table.
select file_name , col1 from table where file_name = "test20170516"
In short, I need to know INPUT__FILE__NAME(hive) eq... | You can do this with the $path pseudo column.
select "$path" from table
| Presto | 44,011,433 | 59 |
I have the following query that I am trying to run on Athena.
SELECT observation_date, COUNT(*) AS count
FROM db.table_name
WHERE observation_date > '2017-12-31'
GROUP BY observation_date
However it is producing this error:
SYNTAX_ERROR: line 3:24: '>' cannot be applied to date, varchar(10)
This seems odd to me. Is t... | You need to use a cast to format the date correctly before making this comparison. Try the following:
SELECT observation_date, COUNT(*) AS count
FROM db.table_name
WHERE observation_date > CAST('2017-12-31' AS DATE)
GROUP BY observation_date
Check it out in Fiddler: SQL Fidle
UPDATE 17/07/2019
In order to reflect comm... | Presto | 51,269,919 | 58 |
Is there any analog of NVL in Presto DB?
I need to check if a field is NULL and return a default value.
I solve this somehow like this:
SELECT
CASE
WHEN my_field is null THEN 0
ELSE my_field
END
FROM my_table
But I'm curious if there is something that could simplify this code.
| The ISO SQL function for that is COALESCE
coalesce(my_field,0)
https://prestodb.io/docs/current/functions/conditional.html
P.S. COALESCE can be used with multiple arguments. It will return the first (from the left) non-NULL argument, or NULL if not found.
e.g.
coalesce (my_field_1,my_field_2,my_field_3,my_field_4,... | Presto | 43,275,356 | 42 |
Why is Presto faster than Spark SQL?
Besides what is the difference between Presto and Spark SQL in computing architectures and memory management?
| In general, it is hard to say if Presto is definitely faster or slower than Spark SQL. It really depends on the type of query you’re executing, environment and engine tuning parameters. However, what I see in the industry(Uber, Neflix examples) Presto is used as ad-hock SQL analytics whereas Spark for ETL/ML pipelines.... | Presto | 50,014,017 | 41 |
Looking at the Date/Time Athena documentation, I don't see a function to do this, which surprises me. The closest I see is date_trunc('week', timestamp) but that results in something like 2017-07-09 00:00:00.000 while I would like the format to be 2017-07-09
Is there an easy function to convert a timestamp to a date?
| The reason for not having a conversion function is, that this can be achieved with a type cast.
So a converting query would look like this:
select DATE(current_timestamp)
| Presto | 51,292,219 | 29 |
I'm trying to obtain a random sample of N rows from Athena. But since the table from which I want to draw this sample is huge the naive
SELECT
id
FROM mytable
ORDER BY RANDOM()
LIMIT 100
takes forever to run, presumably because the ORDER BY requires all data to be sent to a single node, which then shuffles and orders ... | Athena is actually behind Presto. You can use TABLESAMPLE to get a random sample of your table.
Lets say you want 10% sample of your table, your query will be something like:
SELECT id FROM mytable TABLESAMPLE BERNOULLI(10)
Pay attention that there is BERNOULLI and SYSTEM sampling.
Here is the documentation for it.
| Presto | 44,510,714 | 28 |
I am running a query like:
SELECT f.*, p.countryName, p.airportName, a.name AS agentName
FROM (
SELECT
f.outboundlegid,
f.inboundlegid,
f.querydatetime,
cast(f.agent as bigint) as agent,
cast(f.querydestinationplace as bigint) as querydestinationplace,
f.queryoutbo... | I have been facing this problem since the begining of Athena, the problem is the ORDER BY clause. Athena is just an EMR cluster with hive and prestodb installed. The problem you are facing is: Even if your query is distributed across X numbers of nodes, the ordering phase must be done by just a single node, the master ... | Presto | 54,375,913 | 26 |
New to presto, any pointer how can I use LATERAL VIEW EXPLODE in presto for below table.
I need to filter on names in my presto query
CREATE EXTERNAL TABLE `id`(
`id` string,
`names` map<string,map<string,string>>,
`tags` map<string,map<string,string>>)
ROW FORMAT SERDE
'org.apache.hadoop.hive.ql.io.parquet.serde.P... | From the documentation: https://trino.io/docs/current/appendix/from-hive.html
Trino [formerly PrestoSQL] supports UNNEST for expanding arrays and maps. Use UNNEST instead of LATERAL VIEW explode().
Hive query:
SELECT student, score
FROM tests
LATERAL VIEW explode(scores) t AS score;
Presto query:
SELECT student, sco... | Presto | 51,314,218 | 23 |
I've got an Athena table where some fields have a fairly complex nested format. The backing records in S3 are JSON. Along these lines (but we have several more levels of nesting):
CREATE EXTERNAL TABLE IF NOT EXISTS test (
timestamp double,
stats array<struct<time:double, mean:double, var:double>>,
dets array<s... | I have skimmed through all the documentation and unfortunately there seems to be no way to do this as of now. The only possible workaround is
converting a struct to a json when querying athena
SELECT
my_field,
my_field.a,
my_field.b,
my_field.c.d,
my_field.c.e
FROM
my_table
Or I would convert the data to ... | Presto | 49,308,410 | 22 |
It's very convenient to be able to set script variables. For example,
SET start_date = 20151201;
SELECT * FROM some_table where date = {$hiveconf:start_date};
Does Presto have this capability?
| You can do this
WITH VARIABLES AS (SELECT VALUE AS VAR1, VALUE AS VAR2)
SELECT *
FROM TABLE CROSS JOIN VARIABLES
WHERE COLUMN = VAR1
| Presto | 34,301,577 | 21 |
I have this CSV file:
reference,address
V7T452F4H9,"12410 W 62TH ST, AA D"
The following options are being used in the table definition
ROW FORMAT SERDE
'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
'quoteChar'='\"',
'separatorChar'=',')
but it still won't recognize the double quotes... | I do this to solve:
1 - Create a Crawler that doesn't overwrite the target table properties, I used boto3 for this but it can be created in AWS console too, by doing this (change the xxx-var):
import boto3
client = boto3.client('glue')
response = client.create_crawler(
Name='xxx-Crawler-Name',
Role='xxx-Put-h... | Presto | 50,354,123 | 20 |
I'm using the latest(0.117) Presto and trying to execute CROSS JOIN UNNEST with complex JSON array like this.
[{"id": 1, "value":"xxx"}, {"id":2, "value":"yy"}, ...]
To do that, first I tried to make an ARRAY with the values of id by
SELECT CAST(JSON_EXTRACT('[{"id": 1, "value":"xxx"}, {"id":2, "value":"yy"}]', '$..i... | This will solve your problem. It is more generic cast to an ARRAY of json (less prone to errors given an arbitrary map structure):
select
TRANSFORM(CAST(JSON_PARSE(arr1) AS ARRAY<JSON>),
x -> JSON_EXTRACT_SCALAR(x, '$.id'))
from
(values ('[{"id": 1, "value":"xxx"}, {"id":2, "value":... | Presto | 32,478,518 | 19 |
I'm working in an environment where I have an S3 service being used as a data lake, but not AWS Athena. I'm trying to setup Presto to be able to query the data in S3 and I know I need the define the data structure as Hive tables through the Hive Metastore service. I'm deploying each component in Docker, so I'd like to ... | There is a workaround, that you do not need hive to run presto. However I haven't tried that with any distributed file system like s3, but code suggest it should work (at least with HDFS). In my opinion it is worth trying, because you do not need any new docker image for hive at all.
The idea is to use a builtin FileHi... | Presto | 48,932,907 | 19 |
I am new to Presto, and can't quite figure out how to check if a key is present in a map. When I run a SELECT query, this error message is returned:
Key not present in map: element
SELECT value_map['element'] FROM
mytable
WHERE name = 'foobar'
Adding AND contains(value_map, 'element') does not work
The data type is a ... | You can lookup a value in a map if the key is present with element_at, like this:
SELECT element_at(value_map, 'element')
FROM ...
WHERE element_at(value_map, 'element') IS NOT NULL
| Presto | 55,426,024 | 19 |
Does Presto SQL really lack TOP X functionality in SELECT statements?
If so, is there a workaround in the meantime?
https://prestodb.io/
| If you simply want to limit the number of rows in the result set, you can use LIMIT, with or without ORDER BY:
SELECT department, salary
FROM employees
ORDER BY salary DESC
LIMIT 10
If you want the top values per group, you can use the standard SQL row_number() window function. For example, to get the top 3 employees ... | Presto | 37,667,265 | 18 |
I have some issue while formatting a timestamp with Amazon Athena service.
select date_format(current_timestamp, 'y')
Returns just 'y' (the string).
The only way I found to format dates in Amazon Athena is trough CONCAT + YEAR + MONTH + DAY functions, like this:
select CONCAT(cast(year(current_timestamp) as varchar), '... | select current_timestamp
,date_format (current_timestamp, '%Y_%m_%d')
,format_datetime (current_timestamp, 'y_M_d')
;
+---------------------+------------+-----------+
| _col0 | _col1 | _col2 |
+---------------------+------------+-----------+
| 2017-05-19 14:46:12 | 2017_05_1... | Presto | 44,064,923 | 18 |
I know that MSCK REPAIR TABLE updates the metastore with the current partitions of an external table.
To do that, you only need to do ls on the root folder of the table (given the table is partitioned by only one column), and get all its partitions, clearly a < 1s operation.
But in practice, the operation can take a v... | You are right in the sense it reads the directory structure, creates partitions out of it and then updates the hive metastore. In fact more recently, the command was improved to remove non-existing partitions from metastore as well. The example that you are giving is very simple since it has only one level of partition... | Presto | 53,667,639 | 18 |
How do I check if a map has no keys in Presto? If I have a way to check if an array is empty, I can use the map_keys function to determine if the map is empty.
| You can use the cardinality function: https://prestodb.io/docs/current/functions/array.html#cardinality
select cardinality(array[]) = 0;
_col0
-------
true
(1 row)
| Presto | 44,192,105 | 17 |
I am trying to do what I think is a simple date diff function but for some reason, my unit value is being read as a column ("dd") so I keep getting a column cannot be resolved error
I am using AWS Athena
My code is this
SELECT "reservations"."id" "Booking_ID"
, "reservations"."bookingid" "Booking_Code"
, "reser... | Athena is based on Presto. See Presto documentation for date_diff() -- the unit is regular varchar, so it needs to go in single quotes:
date_diff('day', ts_from, ts_to)
| Presto | 58,326,786 | 17 |
I have timestamps stored in time since epoch (ms) and I would like to query and display results using a date formatted like 'yyyy-mm-dd'.
| cast(from_unixtime(unixtime) as date)
See https://prestodb.io/docs/current/functions/datetime.html for more datetime functions.
| Presto | 44,420,926 | 16 |
This question is primarily about older versions of PrestoSQL, which have been resolved in the (now renamed) Trino project as of versions
346. However, Amazon's Athena project is based off of Presto versions 0.217 (Athena Engine 2) and 0.172 (Athena Engine 1), which does have the issues described below. This question wa... |
ROWS are literally number of rows before and after that you want to aggregate. So ORDER BY day ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING will end up with 3 rows: the curnet row 1 row before and 1 row after, regardless of the value of orderdate.
RANGE will look at the values of orderdate and will decide what should be a... | Presto | 60,302,379 | 16 |
I'm getting values from nested maps and it's hard to figure out what data type each value is. Is there a typeof function that can tell me the data type of each value?
| Yes, there is the typeof function:
presto> select typeof(1), typeof('a');
_col0 | _col1
---------+------------
integer | varchar(1)
(1 row)
| Presto | 44,192,096 | 15 |
I have a column in my dataset that has a datatype of bigint:
Col1 Col2
1 1519778444938790
2 1520563808877450
3 1519880608427160
4 1520319586578960
5 1519999133096120
How do I convert Col2 to the following format:
year-month-day hr:mm:ss
I am not sure what format my current col... | Have you tried to use functions like from_unixtime? You could use it to convert unix time to timestamp, then you could use date_format to display it in way you want. Notice that in your example your unix time is with microseconds, so you might want to convert it first to milliseconds.
I have not tested that but I am as... | Presto | 50,050,603 | 15 |
In Presto
SHOW SCHEMAS; returns all schemas
SHOW TABLES FROM foo; returns all tables for foo schema
Is there a simple way to return tables from all schemas in Presto?
| You can use select table_schema, table_name from information_schema.tables;
| Presto | 40,938,321 | 14 |
I like to convert my timestamp columns to date and time format. How should I write the query from presto? my timestamp is UTC time. Thank you very much
Timestamp format"1506929478589"
After query convert it looks like "2016-10-25 21:04:08.436"
| You can convert timestamp to date with cast(col as date) or date(col).
| Presto | 46,886,856 | 14 |
Is this possible in SQL (preferably Presto):
I want to reshape this table:
id, array
1, ['something']
1, ['something else']
2, ['something']
To this table:
id, array
1, ['something', 'something else']
2, ['something']
| In Presto you can use array_agg. Assuming that on input, all your arrays are single-element, this would look like this:
select id, array_agg(array[0])
from ...
group by id;
If, however, your input arrays are not necessarily single-element, you can combine this with flatten, like this:
select id, flatten(array_agg(arra... | Presto | 52,501,221 | 14 |
It seems like there is no native function for that purpose in Presto SQL. Do you know any way to efficiently aggregate a group and return its median?
| approx_percentile() should be a reasonable approach. Assuming a table like mytable(id, val), that you want to aggregate by id:
select id, approx_percentile(val, 0.5) median_val
from mytable
group by id
| Presto | 64,030,409 | 14 |
typically to create a table in Presto (from existing db tables), I do:
create table abc as (
select...
)
But to make my code simple, I've broken out subqueries like this:
with sub1 as (
select...
),
sub2 as (
select...
),
sub3 as (
select...
)
select
from sub1 join sub2 on ...
join sub3 on ...
Where do I... | This is possible with an INSERT INTO not sure about CREATE TABLE:
INSERT INTO s1
WITH q1 AS (...)
SELECT * FROM q1
Maybe you could give this a shot:
CREATE TABLE s1 as
WITH q1 AS (...)
SELECT * FROM q1
| Presto | 42,563,301 | 13 |
In my case, Presto connects to a MySQL database which has been configured to be case-insensitive. But any search through Presto seems to be case-sensitive.
Questions:
1) Is there a way to configure Presto searches to be case-insensitive? If not, can something be changed in the Presto-MySQL connector to make the searche... | You have to explicitly ask for case-insensitive comparison by normalizing compared values either to-lower, or to-upper, like this:
select * from table where lower(name) like '%a%';
select * from table where lower(name) = lower('Adam');
| Presto | 42,850,329 | 13 |
This query in Presto:
select *,
cast(ts_w_tz as timestamp) as ts,
cast(substr(cast(ts_w_tz as varchar), 1, 23) as timestamp) as local_ts_workaround
from (select timestamp '2018-02-06 23:00:00.000 Australia/Melbourne' as ts_w_tz);
Returns:
ts_w_tz | ts | ... | It seems like there's no great solution, but building off of the previous answer, I like this a little better... see the date_format_workaround column:
select *,
cast(from_iso8601_timestamp(date_format(ts_w_tz, '%Y-%m-%dT%H:%i:%s')) as timestamp) as date_format_workaround,
cast(ts_w_tz as timestamp) as ts,
cast(s... | Presto | 48,633,900 | 13 |
I have a very simple csv file on S3
"i","d","f","s"
"1","2018-01-01","1.001","something great!"
"2","2018-01-02","2.002","something terrible!"
"3","2018-01-03","3.003","I'm an oil man"
I'm trying to create a table across this using the following command
CREATE EXTERNAL TABLE test (i int, d date, f float, s string)
RO... | In fact, it is a problem with the documentation that you mentioned. You were probably referring to this excerpt:
[OpenCSVSerDe] recognizes the DATE type if it is specified in the UNIX
format, such as YYYY-MM-DD, as the type LONG.
Understandably, you were formatting your date as YYYY-MM-DD. However, the documentatio... | Presto | 52,564,194 | 13 |
Currently, my table has three different fields, id1, id2 and actions. action is of type string. For example, my table looks something like the table given below:
id1 | id2 | actions
---------------------------
"a1" "a2" "action1"
"b1" "b2" "action2"
"a1" "a2" "action3"
If the values o... | Try using ARRAY_JOIN with ARRAY_AGG:
SELECT
id1,
id2,
ARRAY_JOIN(ARRAY_AGG(actions), ',') actions
FROM yourTable
GROUP BY
id1,
id2;
| Presto | 55,370,212 | 13 |
Recently, I've experienced an issue with AWS Athena when there is quite high number of partitions.
The old version had a database and tables with only 1 partition level, say id=x. Let's take one table; for example, where we store payment parameters per id (product), and there are not plenty of IDs. Assume its around 10... | This is impossible to properly answer without knowing the amount of data, what file formats, and how many files we're talking about.
TL; DR I suspect you have partitions with thousands of files and that the bottleneck is listing and reading them all.
For any data set that grows over time you should have a temporal part... | Presto | 59,488,379 | 13 |
I have a list of creation time stamps and ending time stamps , i would like to get the amount of seconds last from creation to ending . could not find any way to do that without using UNIX time stamp (which i dont have at the moment) .
something like that :
datediff('second',min(creation_time),max(ending_time))
crea... | date_diff
date_diff('second', min(creation_time),max(ending_time))
| Presto | 42,899,288 | 12 |
I'm running a query with a
select bar_tbl.thing1
from foo
cross join unnest(bar) as t(bar_tbl)
And got the error Error Query failed: Cannot unnest type: row
Why?
The bar column looks like this {thing1=abc, thing2=def}
| Turns out I was trying to expand a row, which doesn't make sense.
I should have just done
select bar.thing1
from foo
| Presto | 49,949,652 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.