Oren Eini

aka Ayende Rahien

Oren Eini

CEO of RavenDB

a NoSQL Open Source Document Database

Get in touch with me:

oren@ravendb.net +972 52-548-6969

Posts: 7,616
|
Comments: 51,246

Copyright ©️ Ayende Rahien 2004 — 2025

Privacy Policy · Terms
filter by tags archive
AI Agents, powered by your database - Bring AI into your applications with context, tools, and your data

Geo Location & Spatial Searches with RavenDB–Part III-Importing

time to read 7 min | 1264 words

The following are sample from the data sources that MaxMind provides for us:

image

image

The question is, how do we load them into RavenDB?

Just to give you some numbers, there are 1.87 million blocks and over 350,000 locations.

Those are big numbers, but still small enough that we can work with the entire thing in memory. I wrote a quick & ugly parsing routines for them:

public static IEnumerable<Tuple<int, IpRange>> ReadBlocks(string dir)
{
 using (var file = File.OpenRead(Path.Combine(dir, "GeoLiteCity-Blocks.csv")))
 using (var reader = new StreamReader(file))
 {
 reader.ReadLine(); // copy right
 reader.ReadLine(); // header
 string line;
 while ((line = reader.ReadLine()) != null)
 {
 var entries = line.Split(',').Select(x => x.Trim('"')).ToArray();
 yield return Tuple.Create(
 int.Parse(entries[2]),
 new IpRange
 {
 Start = long.Parse(entries[0]),
 End = long.Parse(entries[1]),
 });
 }
 }
}
public static IEnumerable<Tuple<int, Location>> ReadLocations(string dir)
{
 using (var file = File.OpenRead(Path.Combine(dir, "GeoLiteCity-Location.csv")))
 using (var reader = new StreamReader(file))
 {
 reader.ReadLine(); // copy right
 reader.ReadLine(); // header
 string line;
 while ((line = reader.ReadLine()) != null)
 {
 var entries = line.Split(',').Select(x => x.Trim('"')).ToArray();
 yield return Tuple.Create(
 int.Parse(entries[0]),
 new Location
 {
 Country = NullIfEmpty(entries[1]),
 Region = NullIfEmpty(entries[2]),
 City = NullIfEmpty(entries[3]),
 PostalCode = NullIfEmpty(entries[4]),
 Latitude = double.Parse(entries[5]),
 Longitude = double.Parse(entries[6]),
 MetroCode = NullIfEmpty(entries[7]),
 AreaCode = NullIfEmpty(entries[8])
 });
 }
 }
}
private static string NullIfEmpty(string s)
{
 return string.IsNullOrWhiteSpace(s) ? null : s;
}

And then it was a matter of bringing it all together:

var blocks = from blockTuple in ReadBlocks(dir)
 group blockTuple by blockTuple.Item1
 into g
 select new
 {
 LocId = g.Key,
 Ranges = g.Select(x => x.Item2).ToArray()
 };
var results =
 from locTuple in ReadLocations(dir)
 join block in blocks on locTuple.Item1 equals block.LocId into joined
 from joinedBlock in joined.DefaultIfEmpty()
 let _ = locTuple.Item2.Ranges = (joinedBlock == null ? new IpRange[0] : joinedBlock.Ranges)
 select locTuple.Item2;

The advantage of doing things this way is that we only have to write to RavenDB once, because we merged the results in memory. That is why I said that those are big results, but still small enough for us to be able to process them easily in memory.

Finally, we wrote them to RavenDB in batches of 1024 items.

The entire process took about 3 minutes and wrote 353,224 documents to RavenDB, which include all of the 1.87 million ip blocks in a format that is easy to search through.

In our next post, we will discuss actually doing searches on this information.

Tweet 2 comments
Tags:

Related posts that you may find interesting:

18 Jun 2012 Geo Location & Spatial Searches with RavenDB–Part I–Setup
19 Jun 2012 Geo Location & Spatial Searches with RavenDB–Part II–Modeling
22 Jun 2012 Geo Location & Spatial Searches with RavenDB–Part V-Spatial Searching

Comments

Richard

Hi,

what hardware setup did you use for this? As I am trying to do this on my machine, which is a i7-870 quad core with 8Gb mem. It took at least 30 mins to write a 100k locations. I have the server running on the same machine as the client app. I would be interested to see the actual code for writing to the server. For now I use skip/take 1024 items and store each item, finishing with a savechanges. For each batch I use a new session, else I get a out-of-memory exception...

Cheers,

Richard

Actually took me 01:25:10 for importing all locations, i must be doing something wrong...

Comment preview

Comments have been closed on this topic.

Markdown formatting

ESC to close

Markdown turns plain text formatting into fancy HTML formatting.

Phrase Emphasis

*italic* **bold**
_italic_ __bold__

Links

Inline:

An [example](http://url.com/ "Title")

Reference-style labels (titles are optional):

An [example][id]. Then, anywhere
else in the doc, define the link:
 [id]: http://example.com/ "Title"

Images

Inline (titles are optional):

![alt text](/path/img.jpg "Title")

Reference-style:

![alt text][id]
[id]: /url/to/img.jpg "Title"

Headers

Setext-style:

Header 1
========
Header 2
--------

atx-style (closing #'s are optional):

# Header 1 #
## Header 2 ##
###### Header 6

Lists

Ordered, without paragraphs:

1. Foo
2. Bar

Unordered, with paragraphs:

* A list item.
 With multiple paragraphs.
* Bar

You can nest them:

* Abacus
 * answer
* Bubbles
 1. bunk
 2. bupkis
 * BELITTLER
 3. burper
* Cunning

Blockquotes

> Email-style angle brackets
> are used for blockquotes.
> > And, they can be nested.
> #### Headers in blockquotes
> 
> * You can quote a list.
> * Etc.

Horizontal Rules

Three or more dashes or asterisks:

---
* * *
- - - - 

Manual Line Breaks

End a line with two or more spaces:

Roses are red, 
Violets are blue.

Fenced Code Blocks

Code blocks delimited by 3 or more backticks or tildas:

```
This is a preformatted
code block
```

Header IDs

Set the id of headings with {#<id>} at end of heading line:

## My Heading {#myheading}

Tables

Fruit |Color
---------|----------
Apples |Red
Pears	 |Green
Bananas |Yellow

Definition Lists

Term 1
: Definition 1
Term 2
: Definition 2

Footnotes

Body text with a footnote [^1]
[^1]: Footnote text here

Abbreviations

MDD <- will have title
*[MDD]: MarkdownDeep

FUTURE POSTS

  1. Using multi-staged actions with AI Agents to reduce costs & time - 6 hours from now

There are posts all the way to Nov 17, 2025

RECENT SERIES

  1. Recording (18):
    29 Sep 2025 - How To Run AI Agents Natively In Your Database
  2. Webinar (8):
    16 Sep 2025 - Building AI Agents in RavenDB
  3. RavenDB 7.1 (7):
    11 Jul 2025 - The Gen AI release
  4. Production postmorterm (2):
    11 Jun 2025 - The rookie server's untimely promotion
  5. RavenDB News (2):
    02 May 2025 - May 2025
View all series

Syndication

Main feed ... ...
Comments feed ... ...
}

AltStyle によって変換されたページ (->オリジナル) /